#!/usr/bin/perl
#
# go
#
# - execute all unit tests
#    and clean up after
#

# load some modules we need
use Cwd;
use File::Spec::Functions;

my $num_tests = 0;
my $num_pass = 0;
my $num_fail = 0;
my @fail_list;

if (@ARGV) {
    # read test directory from the command line
    $home = $ARGV[0];
}
else {
    # get the current working directory
    $home = getcwd();
}

if (defined $ENV{'BINDIR'}) {
  $ENV{'PIC30_CD'}="$ENV{'BINDIR'}/..";
}
elsif (!defined $ENV{PIC30_CD}) {
  print "You must define \$BINDIR or \$PIC30_CD\n";
  exit;
}

$ENV{'COMPILER'}="$ENV{PIC30_CD}";
if ( ! -x "$COMPILER" ) {
  print "$COMPILER is not executable\n"
}

print "\n-----------------\n";
print "Linker Unit Tests\n";
print "-----------------\n";
print "\nTest Directory = $home\n";
print "BINDIR = $ENV{BINDIR}\n";
print "PIC30_CD = $ENV{PIC30_CD}\n";
print "PATH = $ENV{PATH}\n";

$date = `date`;
print "\nTest Run on: $date\n";

# a list of directories to skip
my %skip = (
	operators => 1,
        pdata => 1,
);

# open the test directory
#  and get a list of nested directories
chdir $home;
opendir(DOT, '.');
@dirlist = grep { -d and $_ ne '.' and $_ ne '..' } readdir DOT;
@dirlist = sort @dirlist;

# for each nested directory
foreach $d (@dirlist) {
    chomp $d;
    next if $skip{$d}; # avoid skip list

    chdir catfile($home,$d); # cd to an absolute path

    next if (! -e 'go'); # avoid directories without 'go' scripts

    print "testing $d...\n";
    #print `go` ; # execute the test
    $result = `sh go`;
    $num_tests++;
    if ($result =~ /Pass/)
         { $num_pass++; }
    else
         { $num_fail++; push @fail_list, $d }
    print $result;

    #@files = <*>;
    #print " @files\n"; # list the directory before cleaning

    unlink 'a.out', 'test.out', 'UartOut.txt'; # clean up
    unlink <*.stackdump>, <*.hex>, <*.lst>, <*.map>, <*~>, <*.exe>, <*.o>;
    unlink <temp*>, <*.a>;

    #@files = <*>;
    #print " @files\n"; # list the directory after cleaning
}

closedir DOT;

# print summary
print "------------------------\n";
print "Linker Unit Test Summary\n";
print "------------------------\n\n";
print "$num_tests Total tests in $home\n";
print "$num_pass Tests PASS\n";
print "$num_fail Tests FAIL\n\n";

if ($num_fail) {
    print "Failed Tests: @fail_list\n\n";
}

exit;

