#!/usr/bin/env perl

use Time::gmtime;

$saw=0;
$debug = 0;
if ( $ARGV[0] eq "-l" ) {
   $live = 1;
   shift;
} else {
   $live = 0;
}

if ( $ARGV[0] eq "-a" ) {
   $threshold = "0000-00-00";
   shift;
} else {
    # Pick a threshold date a month ago.
    $gm = gmtime(time()- 30*24*60*60);
    $threshold = sprintf("%04d-%02d-%02d", 1900 + $gm->year() , 1 + $gm->mon(), $gm->mday());
}

print "# threshold date is $threshold\n";


while (<>) {

    ($a,$b,$c,$d) = ($_ =~ m/\s*(\S*)/g) ;

    print "got: $a|$b|$c|$d\n" if ($debug);


    if ($saw && "$a" eq '' ) {
	
	if ($date2 gt $date) {
	    $date = $date2;
	}


	print "blank line\n" if ($debug);
	$saw=0;

	# cleanup product name and 
	$prod =~ s/://o;
	$tarfile =~ s{[^:]*:/usr/kits}{ftp://ftp/KITS};
	$flavor =~ m/([^+]*(\+[V0-9.]+)?)(\+(.*))?/;
	$quals = $4;
	$flavor = $1;

	if ( $quals ne '' ) {
	   $quals = "-q " . $quals;
	   $quals =~ s/\+/:/g;
	}

	if (!$live) {
	    $opts = "-O separate_tables:date-$date";

	    if ( $prod =~ m/\A(cops|edt|flint|numrec_c|numrec_f|pvi|tpu|vx_dart|vx_fscc|vx_mv147|vx_mv162|vx_mv166|vx_mv167|vx_sv30|vx_tape|vxworks68k)\Z/ ) {
	       $opts = "$opts:proprietary";
	       $tarfile =~ s{.*KITS}{ftp://localhost/scratch2/kits};
	    }
	    if ( $prod =~ m/\A(FISION|camac|cps|dbs|dervish|frc|ftt|histoscope|juke|murmur_kit|nedit|ocs|plot_widgets|robin|transport|turtle|ucm|ups)\Z/ ) {
	       $opts = "$opts:fermitools";
	    } 

	    if ($tarfile ne "No") {
		$cmd= "upd migrate -h fnkits.fnal.gov $opts $chain -f $flavor $quals -T $tarfile $prod $vers";

	    } else {
		$cmd = "true";
	    }
	} else {
	    $opts = "-O live:date-$date";
	    $pre = "USER=$declarer";
	    $cmd= "upd migrate $opts $chain -r $home -f $flavor $quals $prod $vers";
	}
	print "# $prod $vers $flavor date is $date threshold $threshold\n";
	if ($date ge $threshold) {
	    print "$pre $cmd || echo failed: $cmd >&2\n";
	}

	$chain="";
	$quals="";

    }
    $_ = "${a}_${b}_${c}";
    if (/Verbose_versions_of/)	{ $prod="$d";   			next;}
    if (/.*_Instance_of/) 	{ $saw=1; $chain="-g $a"; 		next;}
    if (/Instance(_?):_.*/)   	{ $saw=1; $vers= $1 eq "_"?"$c":$b; 	next;}
    if (/Flavor(_?):_.*/)   	{ $saw=1; $flavor= $1 eq "_"?"$c":$b; 	next;}
    if (/Home_dir(_?):_.*/)   	{ $saw=1; $home= $1 eq "_"?"$c":$b; 	next;}
    if (/Declarer(_?):_.*/)   	{ $saw=1; $declarer= $1 eq "_"?"$c":$b;	next;}
    if (/Flavor(_?):_.*/)   	{ $saw=1; $flavor= $1 eq "_"?"$c":$b; 	next;}
    if (/Tarfile[^_]*(_?):_.*/) { $saw=1; $tarfile= $1 eq "_"?"$c":$b; 	next;}
    if (/Declared_date:.*/)	{ $saw=1; 
				  $date=$c;
				  $date=~ s/(\d+)-(\d+)-(\d+)/19$3-0$1-0$2/;
				  $date=~ s/(\d{4})-0*(\d{2})-0*(\d{2})/$1-$2-$3/;
				  next;
				}
    if (/Made_.*_on:.*/)	{ $saw=1; 
				  $date2=$d;
				  $date2=~ s/(\d+)-(\d+)-(\d+)/19$3-0$1-0$2/;
				  $date2=~ s/(\d{4})-0*(\d{2})-0*(\d{2})/$1-$2-$3/;
				}
}
