#!/usr/bin/perl -w

use Cwd;

$dir = cwd(); 

#dir can be /home/scifi or /home/scifi2 
if ($dir eq "/home/scifi2/") {
    exit; 
}

#thread is quathena, quathena-1, quathena-2, etc. 
$thread = "$0";
$thread =~ s#./bin/##; 

if ($thread eq "quathena") {
    exit; 
}
elsif ($thread ne "quathena-1") {
    exit; 
}

$qLock = "$dir/lock/quathena-lock"; 
$qUnlock = "$dir/lock/quathena-unlock";
$qAbort = "$dir/lock/quathena-abort"; 
#$qNoAbort = "$dir/lock/quathena-no-abort"; 
$qPause = "$dir/lock/quathena-pause"; 
$qContinue = "$dir/lock/quathena-continue"; 

$qAnalyze = "$dir/bin/quathena-analyze";
$qSummary = "$dir/bin/summary.pause";

$data = "$dir/public_html/data/"; 

$metaSize = 4;  

$retrywarn = 3; 

$retry = 6; 

$cluster = 'club.med.harvard.edu -l await /home/await/bin/pQmars.pl'; 

#add other clusters here but need a weighting system first

if (-e $qLock ) {
    exit; 
}
if (-e $qAbort ) {
    exit; 
}

#don't buffer STDOUT or STDERR; from perl cookbook recipe 7.12 
select((select(STDOUT), $| = 1)[0]);
select((select(STDERR), $| = 1)[0]);

rename($qUnlock, $qLock) 
    || die "failed to rename quathena-unlock $!";

chdir "$data/incoming"; 

@files = grep {-f} glob "*";
#create hash with file and file last modified date
$fNT{$_} = sprintf "%010d", (stat $_)[9] for @files;
#the first element of the sorted hash
$oldestIntervention = ( sort {$fNT{$a} <=> $fNT{$b}} keys %fNT )[0];

chdir "$data/meta"; 

unless (-e "tmp/current.meta.qcz" ) {
    die "failed to find Metaworld\n";
}

$base = sprintf("%8.8X",time());

if (-e "$base.meta.qcz") {
    die "clock skew (metaworld) $!"; 
}
    
if ($oldestIntervention ) {

    if (-e "../done/$base.i") {
	die "clock skew (intervention) $!"; 
    }
     
    rename ("../incoming/$oldestIntervention", "../done/$base.i")
	|| die "failed to rename Intervention $!";
  
    $command = "gzip -c ../done/$base.i |".
	    "bzip2 >tmp/current.i.gz.bz2"; 

    print "$command\n";
    
    if (system ($command) || system ("bzip2 -t tmp/current.i.gz.bz2")) {
	die "failed to compress Intervention $!";
    }    
    $oldestIntervention = "tmp/current.i.gz.bz2"; 

    if (-e $qPause) {
	rename ($qPause, $qContinue) 
           || die "failed to rename quathena-pause $!";	
    }
}
else {
    $oldestIntervention=""; 
}

if (-e $qPause) {
    rename($qLock, $qUnlock) || 
	warn "paused but failed to rename quathena-lock $!";
    exit; 
}
 
print "Job starting @ ", scalar localtime, "\n" ;


for ($i = 1; $i <= $metaSize; $i++) {

    unless (defined ($pid = fork)) { 
	die "cannot fork: $!";
    }
    unless ($pid) { 	 

	$world = sprintf("%8.8X.qcw.gz.bz2",$i);

	$command = 
	    "tar -Ojxf tmp/current.meta.qcz $world |".
	    "cat - $oldestIntervention |".
	    "ssh -o \"compression no\" $cluster".
	    " >tmp/$world";
	
	$verify = 
	    "bzcat tmp/$world |".
	    "zcat |".
	    'grep MD5\.*\(1 |'.
	    "cut -c 1-5,38- |".
	    "diff -q tmp/current.qcw.verify -"; 

	$try = 0; 
	do { 
	    if ($try >= $retry) { 
		print "ABORTING: tried *** $command *** $try times\n";
		exit; 
	    }
	    if ($try >= $retrywarn) {
		print "tried *** $command *** $try times\n";
	    }
	    $try++; 
	} while (system($command) || system ($verify)); 

	exit;  # catch with wait()  
    }
}	

while ($i--) {
  wait(); 
}

print "verifying $base.meta.qcz\n"; 

chdir "$data/meta/tmp"; 

system ("tar -jcf new.meta.qcz *.qcw.gz.bz2");

$command = 
    "tar -Ojxf new.meta.qcz |".
    "bzcat |".
    "zcat |".
    'grep MD5\.*\(1 |'.
    "cut -c 1-5,38- |".
    "diff -q current.meta.verify -"; 

if (system ($command)) {
    print "$command\n";
    die "fatal problem with metaworld file: $!"; 
}

rename ("current.meta.qcz", "../$base.meta.qcz") 
    || die "failed to rename old Metaworld $!";

rename ("new.meta.qcz", "current.meta.qcz") 
    || die "failed to rename new Metaworld $!";

#learning perl Ch.13
foreach (<*.bz2>) { # step through a list of .bz2 files
    unlink || die "having trouble deleting $_: $!";
}

chdir "$dir";

if (system ("$qAnalyze $dir $thread")) {
    die "failed analysis $!"; 
}

chdir "$dir/public_html/data/meta/tmp"; 

#pause? 

$continue = 
    'tar -Ojxf current.meta.qcz | bzcat|zcat| grep "M(1)" |'.
    "diff -q $qSummary -";

unless (system($continue)) {
    rename ($qContinue, $qPause) || 
       warn "failed to rename quathena-continue $!";
}

rename($qLock, $qUnlock) || 
   die "(nearly done but) failed to rename quathena-lock $!";

print "Job finished @ ", scalar localtime, "\n" ;

if (-e $qPause) { 
    print "\npausing...\n";
}
if (-e $qAbort) {
    print "\naborting...\n"; 
}
