#!/usr/local/bin/perl -w
# Execute as master.pl list of directories
# wwwdir is a directory -- program will check wwwdir/seporggifdir
# lower (defaults to 5000) is lower limit -- report files smaller than this
# upper (defaults to 100000) is upper limit -- report files larger than this 
#
$lockfile = "/home/A7F/gcf/foils/master";
$mailprog = '/usr/lib/sendmail';
$count = 0;
while (!&LockDatabase($lockfile)) { # Sleep for a second
        sleep(1);
        ++$count;
        die("Cannot run master as lock unavailable") if($count > 20);
}
#
$rerun=1;
$lookaterrors=0;
#
$irun=0;
$basedir= `pwd`;
chomp($basedir);
while(defined($ARGV[$irun]))	{
	$dirfoilset=$ARGV[$irun];
	++$irun;
	unless( -e $dirfoilset) {
                print "Isnt even a file!\n";
                next;
        }
        if( -l $dirfoilset) {
                print "Unsafe to process link $dirfoilset -- go to correct directory\n";
                next;
        }
	print "Checking Directory ",$dirfoilset,"\n";
	unless(-d $dirfoilset) {
		print "Isnt a directory!\n";
		next;
	}
	unless( (-e $dirfoilset."/processed") || (-e $dirfoilset."/colors") ) {
		print "No Processed or Color File\n";
		next;
	}
#
#	Unnecessary for Photosets
	if(-e $dirfoilset."/seporggifdir")	{
		print "This is an old version!\n";
		unless( -e $dirfoilset."/colors" )	{
			chdir('progs');
			system("setbasic2 $dirfoilset");
			chdir($basedir);
			chdir($dirfoilset);
			system('runwwwfoil1');
			chdir($basedir);
		}
		else	{ # Scripts
			chdir('progs');
			system("setscript4 $dirfoilset");
			chdir($basedir);
		}
	}
#	END Unnecessary for Photosets
#
	($grab) = <$dirfoilset/seporgimagedir/abstract*>;
	if(defined($grab))	{
		$com="rm $grab";
		system($com);
	}
	($grab) = <$dirfoilset/*script*>;
	if(defined($grab))	{
		$colors=$dirfoilset."/colors";
		if(-e $colors)	{
			open(COLORS,"<".$colors) || die("\nSorry couldn't open ",$colors,"\n");
			$col1=<COLORS>;
			$col2=<COLORS>;
			chomp($col1);
			chomp($col2);
		}
		else	{
			print "error as no color file in script\n";
			next;
		}
		print "Scripted Directory Colours ",$col1,' ',$col2,"\n";
		unless(defined($col1) && defined($col2) )	{
			print"Errors in Colors\n";
		}
		$script=1;
		$com = 'cp masterscript/perswww masterscript/run* masterscript/temp* '.$dirfoilset;
		system($com);
		$com = 'progs/customfoil2.pl '.$dirfoilset.' PURPLE '.$col1.' purple '.$col2;
		system($com);
	}
	else	{
		if( -e $dirfoilset."/colors" )	{
			print "error as color file in NONscript file\n";
			next;
		}
		$script=0;
		$com = 'cp masterbasic/perswww masterbasic/temp* masterbasic/run* '.$dirfoilset;
		system($com);
	}
	if($rerun)	{
		chdir $dirfoilset;
		if( (-e 'totalhtml.html') ||( -e 'mixedhtml.html') )	{
			system('rm totalhtml.html mixedhtml.html');
		}
		system('runwwwfoil2');
		chdir $basedir;
	}
	$lower=5000;
	$upper=200000;
	$dir=$dirfoilset. '/seporggifdir';
	$dir1= $dirfoilset. '/seporgimagedir';
	if((-e $dir) && (-e $dir1))	{
		print "gif and image files exist -- Aborting\n";
		next;
	}
	unless( (-e $dir) || (-e $dir1))     {
		print "Neither gif nor image files exist -- Aborting\n";
		next;
	}
	$dir = $dir1	if( -e $dir1 );
	chdir $dir;
	$error=0;
	$files= `ls`;
	@names=split(/\s+/,$files);
	$max=0;
	$abstract=0;
	foreach $old (@names)	{
		$i=$old;
		$i =~ s/\.(\D*)$//;
		$i =~ s/(^0*)(.+$)/$2/;
		if($i eq 'abstract' )	{
			$abstract=1;
			next;
		}
		$max=$i if($i > $max);
		$numbers[$i] = $old;
		print "Illegal zero foil number ",$old," \n"	if($i==0);
		++$error if($i==0);
	}
	print "Abstract Missing\n" if($abstract==0);
	print "Maximum foil number is ",$max," \n";
	for($i=1;$i <= $max; $i++)	{
		next if(defined($numbers[$i]));
		print "Missing Foil GIF number ",$i,"\n";
		++$error;
	}
	$fatalerror=0;
	foreach $i (@names)	{
		$actual=$i;
		while(-l $actual)	{
			$oldactual=$actual;
			$actual= readlink($actual);
			unless($actual =~ m%^/% )	{
				$oldactual =~ s%([^/]*)$%%;
				$actual = $oldactual.$actual;
			}
			if($actual =~ m%R8E/gcf% )	{
				$actual =~ s%(.*)R8E/gcf%../../..%;
				$com = 'rm '.$i;
				system($com);
				symlink $actual,$i;
			}
		}
		$singlels=`ls -l $actual`;
		@arrayls=split(/\s+/,$singlels);
		$length=$arrayls[3];
		$length=$arrayls[4] if(($length eq 'foilsbmt')||($length eq 'geoff')||($length eq 'dir')||($length eq 'cps600ad')||($length eq 'res')||($length eq 'infosys'));
		unless(defined($length))	{
			print "Missing Link ",$i,"\n";
			$fatalerror=1;
			next;
		}
		print "File size too small ",$length," for ",$i,"\n"	if($length <$lower);
		++$error if($length <500);
		print "File size too large ",$length," for ",$i,"\n"	if($length >$upper);
	}
	chdir $basedir;
#
#	Remove for Photosets
	$added ='/07';
	$added ='/06'	if(-e '/usr/local/archives/public/users/gcf/06/' . $dirfoilset);
	if( $dirfoilset =~m%^dbpp%)    { $added = ''; }
	if($fatalerror || ($lookaterrors && $error))	{
		print "Possible Errors detected -- no WWW copy\n";
	}
	else	{
		$addeddir='';
		if( $dirfoilset =~ m%/% )	{
			$dirfoilset =~ m%(.*)/([^/]*)%;
			$addeddir = '/'.$1;
			mkdir('/home/A7F/gcf/foils' . $addeddir, 0755) unless ( -e '/home/A7F/gcf/foils' . $addeddir);
			mkdir('/usr/local/archives/public/users/gcf' . $addeddir, 0755) unless ( -e '/usr/local/archives/public/users/gcf' . $addeddir);
			if( $added)	{
				mkdir('/usr/local/archives/public/users/gcf' . $added . $addeddir, 0755) unless ( -e '/usr/local/archives/public/users/gcf' . $added . $addeddir);
			}
			$testfile = '/home/A7F/gcf/foils' . $addeddir;
			symlink( '/project/gcf_proj/foils' . $addeddir, $testfile) unless( -e $testfile);
		}
		$testfile = '/home/A7F/gcf/foils/' . $dirfoilset;
		symlink( '/project/gcf_proj/foils/' . $dirfoilset, $testfile) unless( -e $testfile);
		die ('System Error 1 ' . $dirfoilset."\n")	if($dirfoilset eq '' );
		$testfile = '/usr/local/archives/public/users/gcf/'.$dirfoilset;
		if( -l $testfile )	{
			$linkvalue = readlink($testfile);
			unless( $linkvalue =~ m%^/% )	{
				$testfile =~ s%/[^/]*$%/%;
				$testfile = $testfile . $linkvalue;
			}
			else	{
				$testfile = $linkvalue;
			}
		}
		if( -e $testfile )	{
			die ('System Error 2 ' . $testfile ."\n") unless(-e ($testfile.'/perswww'));
			$com = 'rm -r '.$testfile;
			system($com);
			print "Original WWW version ",$dirfoilset,' Deleted',"\n";
   		}
		$com='cp -r '.$dirfoilset.' /usr/local/archives/public/users/gcf'. $added . $addeddir;
		system($com);
		$com = 'progs/setoldlinks.pl ' . '/usr/local/archives/public/users/gcf'. $added . '/' . $dirfoilset;
		system($com);
		if( $added )	{
			$oldlink = '/usr/local/archives/public/users/gcf/'.$dirfoilset;
			if(-l $oldlink)	{
			$com = 'rm '. $oldlink;
			system($com);
			}
			unless( -e '/usr/local/archives/public/users/gcf/'.$dirfoilset )	{
				$nosladded = $added;
				$nosladded =~ s%^/%%;
				$nosladded = '../' . $nosladded if( $addeddir );
				symlink( $nosladded . '/' . $dirfoilset, '/usr/local/archives/public/users/gcf/'.$dirfoilset);
			}
		}
		print "WWW copy ",$dirfoilset,"\n";
	}
#	End Remove for Photosets
#
#	Change foilsets.basic to photosets.basic below for Photo Version
	$com='progs/customfoil1.pl '.$dirfoilset.' foilsets.basic wwwalias foilsbyshorttopic';
	system($com);
}
&UnlockDatabase($lockfile);
exit;
#
sub LockDatabase {
# PURPOSE: Attempt to "lock" the database by creating a lock file.
# INPUTS:  Database file name
# OUTPUTS: A boolean telling if the lock was successful

        my ($dbfile) = @_;

        if (-e "$dbfile.lock") {  # DB is already locked
                return 0;
        }
        else {
                system("touch $dbfile.lock");  # Create the lock file
                return 1;
        }
}

sub UnlockDatabase {
# PURPOSE: Attempt to "unlock" the database by deleting the lock file.
# INPUTS:  Database file name
# OUTPUTS: None (but should probably check that the unlock was successful)

        my ($dbfile) = @_;
        unless( (unlink("$dbfile.lock")) )      {
                open (MAIL, "|$mailprog gcf") || (die("master.pl Can't Mail -- Please contact us")) ;
                print MAIL <<EOF;
From:gcf
To:gcf
Subject:Error in unlink
------------------------------------------------------

Please check master.pl
EOF
                close(MAIL);
        }
}
