# use "*_t" for basename of this file.
# symlink to 21-blah-<perl version string to test>.t.
# e.g.,
#   "21-foo-v5.5.3.t"
#   "21-bar-5.005_003"
#   "21-bar-v5.005003"
# will test varieties of the same perl version string.

use 5.008;
use strict;
use version;
use lib qw( lib t/lib );

use Test::More;
use Test::Deep;

use File::Basename  qw( basename    );
use FindBin         qw( $Bin        );

use lib( "$Bin/../../lib", "$Bin/../lib" );
use Test::KwikHaks;

my $madness = 'Module::FromPerlVer';

*output     = Test::KwikHaks->can( 'output' );

output();

SKIP:
{
    my ( $base, $perl_v )  
    = eval
    {
        Test::KwikHaks::perl_v_from_basename()
    }
    or BAIL_OUT "Missing Perl Version: $@";

    eval
    {
        Test::KwikHaks::test_git_version()
    }
    or skip "Git not available ($@)", 1;

    my $sandbox 
    = eval
    {
        Test::KwikHaks::sandbox_tmpdir()
    }
    or skip "No tempdir: $@";

    output( 'Working directory: ' . basename $sandbox );

    my @found = qx{ git tag -l 'perl/*' 2>&1 };

    $?
    and BAIL_OUT "Failed git tag: non-zero exit $?";

    @found
    or BAIL_OUT "Failed git tag: no ouptut";
 
    my $v_file  = Test::KwikHaks::write_version_file( $perl_v )
    or skip "Failed writing version file.", 1;

    eval
    {
        my @argz    = ( use_git => 1,  version_from => $v_file );

        use_ok $madness => @argz
    }
    or skip "Use failed; $@", 1;

    my $prefix  = $madness->source_prefix;

    is $prefix, 'perl/', "Source prefix: '$prefix' (perl/)";

    for my $found ( $madness->source_files )
    {
        note "Source files:\n", explain $found;

        fail "Extraneous souce files: $found";
    }

    eval
    {
        chomp( my $found = ( qx{ git branch } )[0] );

        ok 0 < index( $found, $prefix ),
        "Found: '$prefix' in '$found'"
        or do
        {
            die "No prefix: '$prefix' in '$found'.\n";
        };

        my $v_rx    = qr{ $prefix (v?[\d._]+) \b }x;

        if
        (
            my ( $tag_v ) = $found =~ $v_rx
        )
        {
            pass "Tag version: '$tag_v'";

            my $i   = version->parse( $tag_v  )->numify;
            my $j   = version->parse( $perl_v )->numify;

            ok $i <= $j, "Tag ($i) <= Perl ($j)";
        }
        else
        {
            fail "No version: '$v_rx'";
            diag "Git status: '$found'";
        }
        
        unlink $v_file;

        1
    }
    or fail "Unable to determine branch: $@";

    # reset the directory to avoid cruft messages from 
    # git status in initial checks.
  
    qx{ 'git checkout HEAD' 2>&1 };
}

done_testing;
__END__
