#! perl

use v5.10;
use strict;
use warnings;
use Path::Tiny;
use Sort::Versions;

use alienfile;

use File::Which;

our $VERSION;

BEGIN {
    ## no critic( Variables::ProhibitReusedNames )
    #<<<
    our $VERSION = 'v4.27.0.1'; # TRIAL VERSION
    #>>>
}

use constant PACKAGE_NAME    => 'trng4';
use constant PACKAGE_VERSION => do {
    my @V = $VERSION =~ /(\d+)(?:[.]|$)/g;
    pop @V;
    join q{.}, @V;
};

use constant TRNG_VERSION => do {
    my @V = $VERSION =~ /(\d+)(?:[.]|$)/g;
    pop @V;
    $V[0] + ( ( $V[1] // 0 ) + ( $V[2] // 0 ) / 100 ) / 100;
};

plugin 'Gather::IsolateDynamic';

plugin PkgConfig => ( pkg_name => PACKAGE_NAME );

share {
    plugin 'Build::CMake';

    start_url( ( path( 'src' )->children( qr/trng4-@{[ TRNG_VERSION ]}/ ) )[0] );

    plugin Download => (
        filter  => qr/(?:\d+[.]\d+[.]\d+)[.](?:tar[.]gz|tgz)$/,
        version => qr/(\d+[.]\d+[.]\d+)[.](?:tar[.]gz|tgz)$/,
    );

    plugin Extract => 'tar.gz';

    patch sub {
        my $build = shift;

        # just in case the distribution doesn't have a patch directory.
        return unless defined $build->install_prop->{patch};
        my $patch = path( $build->install_prop->{patch}, "patch-@{[ TRNG_VERSION ]}", );
        return unless $patch->exists;
        Alien::Build::CommandSequence->new( ["%{patch} -p1 <  $patch"] )->execute( $build );
    };

    meta->after_hook(
        'extract',
        sub {
            my ( $build ) = @_;

            my $trng_src   = $build->install_prop->{download};
            my $catch2_src = ( path( $trng_src )->parent->children( qr/Catch2-*/ ) )[-1];

            require Archive::Tar;

            my $tar     = Archive::Tar->new;
            my $destdir = ( path( q{.} )->children )[0]->child( 'external' );
            $tar->setcwd( $destdir );
            rmdir $destdir->child( 'Catch2' );
            $tar->read( $catch2_src, undef, { extract => 1 } );
            ( $destdir->children( qr/Catch2/ ) )[-1]->move( $destdir->child( 'Catch2' ) );
            1;
        } );

    #<<<
    build [
        [
            '%{cmake}',
            @{ meta->prop->{plugin_build_cmake}->{args} },
            '%{.install.extract}',
        ],
        '%{make}',
        '%{make} test',
        '%{make} install',
    ];
    #>>>

};
