#!/usr/bin/perl -w

# Run each of the shell tests, capturing the output, and reporting passed 
# or failed.

use Cwd;

# Place to put test output to avoid cluttering test/
mkdir 'test_output', 0750;

# Override the users default .darcs settings
$ENV{HOME} = cwd();
mkdir '.darcs';
system 'echo ALL --ignore-times >> .darcs/defaults';
# Used for finding darcs, but may not be defined by the shell
$ENV{PWD} = cwd();

# Put the right darcs first in PATH
my $darcspath="$ENV{HOME}/..";
if ($ENV{DARCS}) {
  # User has asked for a particular darcs...
  my $actualdarcs=`which $ENV{DARCS}`;
  my $darcspath=`dirname "$actualdarcs"`;
}
$ENV{PATH} = "$darcspath:$ENV{PATH}";

# Some environment variables can act as defaults that we don't want
$ENV{EMAIL} = $ENV{DARCS_EMAIL} = 'tester';

# These two environment variables will turn off darcs' "Christmas mode".
# It will make the tests run a tad faster, and make darcs' output
# independent of the testing systems locale and environment.
$ENV{DARCS_DONT_COLOR} = 1;
$ENV{DARCS_DONT_ESCAPE_ANYTHING} = 1;

my $OK = 1;
my @Failures;
my @Passes;

`which bash`;
if( $? != 0 ) {
    die "You need bash to run the shell tests!"
}

for my $test (@ARGV) {
    my $test_out = "test_output/$test.out";

    printf "Running %-40s", "$test ...";

    my $output = `bash $test 2>&1`;

    if( $? == 0 ) {
        push @Passes, $test;
        print " passed.\n";
    }
    else {
        $OK = 0;
        push @Failures, $test;

        print " FAILED!\n";
        print "Output from failed $test:\n$output";
    }
}

my $CWD = cwd();
if ($CWD =~ /bugs/ && $#Passes >= 0) {
  print "Some tests passed:\n";
  print "\t$_\n" for @Passes;
}
if ($OK) {
    print "All tests successful!\n";
}
else {
    print "TESTS FAILED!\n";
    print "\t$_\n" for @Failures;
}

# Exit with non-zero if anything failed.
exit !$OK;
