#!/usr/bin/perl

######################################################################
# Purpose:
#  Check that files are present on local host.  
#  If all are present, return 0.  If any are missing, return 1.
#  
#
# Input:
#       fileset table: file name containing a directory name and filenames
#
# Author: Paula Freeman, some cobbled from Richard Putt's script.
######################################################################

$verbose=0;

# get date/time

  ($sec,$min,$hour,$mday,$mon,$year,$wday,$jday,$isDST) = gmtime;
  $curYear = $year + 1900;
  $curMon = sprintf( "%02d", ( $mon + 1 ) );
  $curMDay = sprintf( "%02d", $mday );
  $curHour = sprintf( "%02d", $hour );
  $curMin  = sprintf( "%02d", $min );
  $YYYYMMDD = $curYear . $curMon . $curMDay;
  $now = $hour*60 + $min;


if ( $#ARGV == 0 ){

   $fileTable=shift;
} else {
   print "usage: $0 <file table> \n";
   exit;
}


# Define hash table

%fileListHash=();


# Open the table

if (! open (TABLE,"$fileTable"))  {
   print "$0: Cannot open $fileTable: $!";
   exit 0;
}

# First line is the directory pattern

$dirLine=<TABLE>;
($baseDir, $dirTime) = split(/\s+/, $dirLine);
chomp $baseDir;
$baseDir =~ s/YYYYMMDD/$YYYYMMDD/g;

$verbose && print "\nChecking for files in $baseDir \n";

# The rest of the lines are the filenames.

while ($filename=<TABLE>) {
   chomp $filename;
   $fileListHash{$filename} = "1";
}

#foreach $key (keys %fileListHash) {
#   print "$key\n";
#}


# Read the directory.
# If directory doesn't exist, and it's still before the 
# directory creation time limit, just exit.  If after
# then generate and error.

if (!opendir(DIR, $baseDir)) {
   print "$0: opendir($baseDir) failed: $!\n";
   exit 1;
}
@dirLines=readdir(DIR);
closedir(DIR);

foreach $f (@dirLines){
   chomp $f;
   $filePath = "$baseDir/$f";
   # next if !-f $filePath;
  if ( exists $fileListHash{$f} ){
    delete $fileListHash{$f} ;
  } else {
#    print "WARNING: File not in table " . $hostname . ":" . $baseDir . "$filePath\n";
  }
}


# Print out names of missing files

@missingFiles = sort keys %fileListHash;
$missedFileCount = scalar( @missingFiles );

#print "number of missing files: $missedFileCount\n";
if ( $missedFileCount != 0) {
   print "\nFiles that are missing: \n\n";
   for $file ( sort keys( %fileListHash ) ){
     print "$baseDir/$file\n";
   }
   exit 1;
} else {
   $verbose && print "\nGOOD: No missing/late files.\n";
   exit 0;
}


 
