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

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

use Cwd             qw( getcwd      );
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' );
*rm_rf      = Test::KwikHaks->can( 'rm_rf' );

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 = Test::KwikHaks::sandbox_path()
    or BAIL_OUT "Non-existant: 'sandbox'", 1;

    chdir $sandbox
    or BAIL_OUT "Failed chdir: '$sandbox', $!", 1;

    output( 'Working directory: ' . getcwd );

    # anything other than .git and .git.tar can be 
    # cleaned up prior to execution to give a reasonable
    # result for status.

    qx{ git checkout HEAD 2>&1 };

    chomp( my @status  = qx{ git status . } );

    output( "Sandox status", @status );

    chomp( 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";

    local $ENV{ PERL_VERSION } = $perl_v;

    use_ok $madness => qw( use_git 1 git_tarball .git.tar )
    or BAIL_OUT "$madness is not usable.";

    my $prefix  = $madness->source_prefix;

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

    for my $found ( $madness->source_files )
    {
        output( "Source files", explain $found );

        # git objects don't return source files 

        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'";
        }

        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__
