#!/usr/bin/perl

use strict;
use warnings;

use Test::More;
use List::MoreUtils qw(none);
use Env::Path ();
use Path::Tiny qw/ path /;
use Test::Differences qw/ eq_or_diff /;

# Remove FCS_TEST_BUILD so we won't run the tests with infinite recursion.
if ( !delete( $ENV{'FCS_TEST_BUILD'} ) )
{
    plan skip_all => "Skipping because FCS_TEST_BUILD is not set";
}

plan tests => 15;

# Change directory to the Freecell Solver base distribution directory.
my $src_path = path( $ENV{"FCS_SRC_PATH"} );

sub test_cmd
{
    local $Test::Builder::Level = $Test::Builder::Level + 1;
    my ( $cmd, $blurb ) = @_;

    my @cmd = ( ref($cmd) eq "ARRAY" ) ? @$cmd : $cmd;

    # These environment variables confuse the input for the harness.
    my $sys_ret = do
    {
        local %ENV = %ENV;
        delete( $ENV{HARNESS_VERBOSE} );

        system(@cmd);
    };

    if ( !ok( !$sys_ret, $blurb ) )
    {
        Carp::confess( "Command ["
                . join( " ", ( map { qq/"$_"/ } @cmd ) )
                . "] failed! $!." );
    }
}

{
    my $temp_dir        = Path::Tiny->tempdir;
    my $before_temp_cwd = Path::Tiny->cwd->absolute;

    chdir($temp_dir);

    # TEST
    test_cmd( [ "cmake", $src_path ], "cmake succeeded" );

    # TEST
    test_cmd( [ "make", "package_source" ],
        "make package_source is successful" );

    my ($version) = $src_path->child("ver.txt")->lines_utf8( { chomp => 1 } );

    my $base     = path("freecell-solver-$version");
    my $tar_arc  = "$base.tar";
    my $arc_name = "$tar_arc.xz";

    # The code starting from here makes sure we can run "make package_source"
    # inside the freecell-solver-$X.$Y.$Z/ directory generated by the unpacked
    # archive. So we don't have to rename it.

    # TEST
    test_cmd( [ "tar", "-xvf", $arc_name ], "Unpacking the arc name" );

    # TEST
    ok( scalar( -d $base ), "The directory was created" );

    my $orig_cwd = Path::Tiny->cwd->absolute;

    chdir($base);

    mkdir("build");
    chdir("build");

    # TEST
    test_cmd( [ "cmake", ".." ], "CMaking in the unpacked dir" );

    # TEST
    test_cmd( [ "make", "package_source" ] );

    # TEST
    test_cmd( [ "tar", "-xvf", $arc_name ],
        "Unpacking the arc name in the unpacked dir" );

    # TEST
    ok( scalar( -d $base ), "The directory was created again" );

    # TEST
    ok(
        scalar( -f path($base)->child("CMakeLists.txt") ),
        "CMakeLists.txt exists",
    );

    # TEST
    ok(
        scalar( -f path($base)->child("HACKING.asciidoc") ),
        "HACKING.asciidoc exists",
    );

    chdir($orig_cwd);

    my $failing_asciidoc_dir = $orig_cwd->child("asciidoc-fail");
    $failing_asciidoc_dir->remove_tree;
    $failing_asciidoc_dir->mkpath;

    my $asciidoc_bin = $failing_asciidoc_dir->child("asciidoc");
    path($asciidoc_bin)->spew_utf8(<<"EOF");
#!$^X
exit(-1);
EOF
    chmod( 0755, $asciidoc_bin );

    # Delete the unpacked directory.
    $base->remove_tree;

    # Now test the rpm building.
    {
        local $ENV{PATH} = $ENV{PATH};

        Env::Path->PATH->Prepend( $failing_asciidoc_dir, );

        # We need to delete the tar.gz/tar.bz2 because rpmbuild -tb may work
        # on them with the .xz still present.
        unlink( map { "$tar_arc.$_" } qw/bz2 gz/ );

        # TEST
        ok( scalar( -e $arc_name ), "Archive exists." );

        open my $tar_fh, "-|", "tar", "-tvf", $arc_name
            or die "Could not open Tar '$arc_name' for opening.";

        my @tar_lines = (<$tar_fh>);
        close($tar_fh);

        chomp(@tar_lines);

        # TEST
        eq_or_diff( [ grep { m{/config\.h\z} } @tar_lines ],
            [], "Archive does not contain config.h files" );

        # TEST
        ok(
            (
                none { m{/freecell-solver-range-parallel-solve\z} }
                @tar_lines
            ),
            "Archive does not contain the range solver executable"
        );

        # TEST
        ok(
            ( none { m{/libfreecell-solver\.a\z} } @tar_lines ),
            "Archive does not contain libfreecell-solver.a"
        );

        # TEST
        test_cmd(
            "rpmbuild -tb $arc_name 2>/dev/null",
            "rpmbuild -tb is successful."
        );
    }

    $failing_asciidoc_dir->remove_tree;

    chdir($before_temp_cwd);
}

__END__

=head1 COPYRIGHT AND LICENSE

This file is part of Freecell Solver. It is subject to the license terms in
the COPYING.txt file found in the top-level directory of this distribution
and at http://fc-solve.shlomifish.org/docs/distro/COPYING.html . No part of
Freecell Solver, including this file, may be copied, modified, propagated,
or distributed except according to the terms contained in the COPYING file.

Copyright (c) 2009 Shlomi Fish

=cut
