#!/usr/bin/env perl

#This is a dumb script: It takes as arguments the minidvodb directory and a merge
# dvodb directory. It finds the newest date ($date) in the minidvodb directory, and 
# for each filename in the minidvodb directory, checks that it exists in the
# merge directory and that it was updated more recently than $date
#
# It's probable that the files listed as old were not merged into the mergedvodb
# and should be merged in.
#
# It's also possible to fool the script by updating something silly in the minidvodb
# directory, giving a fake $date to compare to.  


use warnings;
use strict;
use Getopt::Long qw( GetOptions :config auto_help auto_version gnu_getopt );

my ($mini, $mergy);
GetOptions(
           'minidvodb_path=s' => \$mini, # Database host name
           'mergedvodb_path=s' => \$mergy, # Database name
    ) or die "Unable to parse arguments.\n";
die "Unknown option: @ARGV\n" if @ARGV;
die "Required options: --minidvodb_path  --mergedvodb_path\n"
    unless defined $mini
    and defined $mergy;



my $dir = `pwd`;

#$mini = '/data/ipp005.0/gpc1/catdirs/LAP.ThreePi.20110809.V2.Mini/LAP.ThreePi.20110809.V2.SSky.1583';
#$mergy = '/data/ipp005.0/gpc1/catdirs/LAP.ThreePi.20110809.V2';


my $date_split = `ls -o -1 --time-style +%s --color=never $mini | sort -k 5 | tail -n 1`;
my @splits= split (/\s+/, $date_split);
my $unixdate= $splits[4];
print $date_split;
my $datecom = "date --date=\@"."$unixdate";
my $date =`$datecom`;
chomp $date;
print "Latest date in minidvodb directory: $date or $unixdate (unix)\n";


# 3 days, 

my @list_of_dirs = ('n0000', 'n0730', 'n1500', 'n2230', 'n3000', 'n3730', 'n4500', 'n5230', 'n6000', 'n6730', 'n7500', 'n8230', 's0000', 's0730', 's1500', 's2230', 's3000', 's3730', 's4500', 's5230', 's6000', 's6730', 's7500','s8230');

foreach my $subdir (@list_of_dirs) {


chdir $mini.'/'.$subdir;

print "grabbing $mini/$subdir\n";
my @list_of_mini_files = `ls -1 --color=never `;

chdir $mergy.'/'.$subdir;

print "grabbing $mergy/$subdir\n";

my @list_of_bad = ();

my @list_of_mergy_files = `ls -alrt --time-style +%s > ~/mergy.$subdir.list`;

foreach my $minifile (@list_of_mini_files) {
    chomp $minifile;
    my $mergyfile = `grep $minifile ~/mergy.$subdir.list`;
    
    my @splits = split (/\s+/, $mergyfile); 
  #  print $mergyfile;
    if ($#splits > 5) {
 
	my $num = `date -d "$date" +%s`; 
	if ($splits[5] < $num ) { 
   
	    print "old: $subdir/$minifile\n";
	}
    } else {

	print "dne: $subdir/$minifile\n";

    }
}
}
