#!/usr/bin/env perl

use Cwd;
use strict;

#$ENV{PATH}=
#'/sw/bin:/sbin:/usr/sbin:/usr/bsd:/bin:/usr/bin';



my $currentdir=cwd();

my $scriptsdir;
my $unpack_dir_base;
my $unpack_dir;
my $testresult_dir;
my $lockfile="cgal_testannounce.lock";
#my $announcements_dir="/private/CGAL/testannouncements";
my $announcements_dir="/u/termite/0/user/spion/CGAL/testannouncements";
my $lock_cmd= "/usr/local/bin/lockfile";
my $ftp_results_dir="$currentdir/incoming/";
my $check_file="processed_test_results";
 
my ($cgal_version,$tarname,@results);

$testresult_dir="$currentdir/TESTRESULTS";
$scriptsdir="$currentdir";
$unpack_dir_base="$currentdir";


sub make_unpackdir()
{
    my $dirno = 1;
    my $TMPDIR;
    $TMPDIR = "$unpack_dir_base/TMP$dirno";
    while ( -f $TMPDIR or -d $TMPDIR ) {
        ++$dirno;
        $TMPDIR = "$unpack_dir_base/TMP$dirno";
    }
    mkdir($TMPDIR,0770) or die "Cannot create temporary directory $TMPDIR\n";
    $unpack_dir = $TMPDIR;
}

sub unpack_results{
    chdir $unpack_dir or die;
    my $filename="$ftp_results_dir/$_[0]";
    system "cp $ftp_results_dir/$_[0] $_[0]";
    system "chmod 644 $_[0]";
    system("gunzip", "$_[0]")== 0 
	or die "Could not gunzip $_[0]\n";
    @results=grep /tar$|tar\.gz$/, `tar tf ${tarname}`;
    chomp @results;
    system("tar", "xf", ${tarname}, @results);
    if( ($? != 0) || (@results  == 0) ) {
        print TESTRESULTSLOG "(EE) Cannot read tar file \"${tarname}\"!\n";
    }
    else {
        print TESTRESULTSLOG "(II) Processing tar file \"${tarname}\"...\n";
        system("$scriptsdir/to_zipped_format", "-v", $cgal_version, @results)==0
            or die "to_zipped_format failed on \"$filename\". Test collection not installed.\n";
    }
}


sub install_results()
{
  if (-d $testresult_dir) {
    chdir $testresult_dir or die;    
  } else {
    mkdir $testresult_dir or die;
    chdir $testresult_dir or die;
  }
  if (-d $cgal_version) {
    chdir $cgal_version or die;    
  } else {
    mkdir $cgal_version or die;
    chdir $cgal_version or die;
  }
    my $resultfile;
    for $resultfile (@results) {
        $resultfile =~ s/\.gz//;
        system('tar','--force-local','-xf',"${unpack_dir}/${resultfile}")==0 or die;
#        unlink "${unpack_dir}/$resultfile";
    }
    chdir ".." or die;
#    system("./create_testresult_page", $cgal_version);

# clean up stuff in UNPACK_DIR

    chdir $unpack_dir or die;
#    unlink $tarname;
#    notify();

}

# Save the content of $check_file in the hash %check_file_content, to avoid
# opening, reading, and closing that file at every call of the function
# `exist_in_file` (called thousands of times)
my %check_file_content;
open my $fh, $check_file || die ("Could not open $check_file");
while (my $contents = <$fh>){
    chop $contents;
    $check_file_content{$contents} = 1;
}
close $fh;

#return 0 if it exists and 1 otherwise 
sub exist_in_file{
  if ( $check_file_content{$_[0]} == 1) {
    return 0;
  } else {
    return 1;
  }
}


#first argument is a string
sub append_to_file{
  chdir($currentdir);

  if ( -w $check_file ) {
      open FILE, ">> $check_file" || die ("Could not open $check_file");
  } else {
      open FILE, "> $check_file" || die ("Could not open $check_file");
  }
  print FILE "$_[0]\n";
  close FILE;
}


open (TESTRESULTSLOG, ">>", "./test_results.log")
    or die "Could not open test_results.log\n";

my $dir_h;
my $i;
my $is_good;
my $res;
chdir($currentdir) || die("Could not chdir to $currentdir");
opendir($dir_h, $ftp_results_dir) || die("The ftp directory could no be opened");
while( $i=readdir($dir_h)){
  next if($i eq ".");
  next if ($i eq "..");
  $is_good=1;
  if ( $i =~ m/^(CGAL-\d+\.\d+-Ic?-\d+)[-_]/ ) {
    $cgal_version=$1;
  } else {
    if ( $i =~ m/^(CGAL-\d+\.\d+\.\d+-Ic?-\d+)[-_]/ ) {
      $cgal_version=$1;
    } else {
      if ( $i =~ m/^(CGAL-\d+\.\d+\.\d+)[-_]/ ) {
        $cgal_version=$1;
      } else {
        if ( $i =~ m/^(CGAL-\d+\.\d+)[-_]/ ) {
          $cgal_version=$1;
        } else {
          # die "$i is not a valid name for a testresult collection.\n";
	  $is_good=0;
        }
      }
    }
  }
  if ( $is_good == 1 ){
    if ( -s "$ftp_results_dir/$i" &&
         exist_in_file($i) == 1 &&
         system("lsof", "-w", "$ftp_results_dir/$i") != 1 ){
      system "cp $ftp_results_dir/$i $i";
      system "chmod 644 $i";
      $res = system "gunzip -t $i";
      system "rm -rf $i";
      if ( $res == 0 ){
        append_to_file($i);
        $tarname=`basename $i .gz`;
        chomp $tarname;
        make_unpackdir();
        eval {unpack_results($i)} && eval{install_results()};
        $@ && warn $@;
        chdir($unpack_dir_base);
        system('rm','-rf',$unpack_dir);
        system "./create_testresult_page $cgal_version";
      }
    }
  }    
}
closedir($dir_h);
close (TESTRESULTSLOG);
