#!/usr/bin/perl

#
# This program is scheduled to run on pg1
#

#
# allband = 0xF1
# antenna = 0xF0 merge
#           0xF1 allant
#
# Base start time on the first usc contact of the day in the contacts file for the day
# (20061029_contacts.txt appears not to have any usc passes - thats because it was a
# sunday...)
# 20061101_contacts.txt msp1 is first real, so maybe look for first real contact time
# and use that as the start time. Also sundays do not have any real time contacts...
#

use Time::Local;
use Date::Calc;
use Env qw(EGSE_SW_LIB);

# Instead of die-ing would be better to report the error in a file somewhere
# and then exit. This applies to all instances of die of course. Todo.

do "$EGSE_SW_LIB/date_calc.pl"     || die "Can't do date_calc.pl: $!\n";
do "$EGSE_SW_LIB/pipeline_defs.pl" || die "Can't do pipeline_defs.pl: $!\n";

open(MLOG, ">> $pipeline_log/pipeline_log_rescue.txt") || die "Can't open $pipeline_log/$pipeline_log_rescue.txt for writing: $!";
print MLOG scalar(localtime), " (JST) rescue_cleanup started ";

# The start time will either be passed in (interactive mode)
# or will be generated from cron using todays date minus 7 days

$state = "cron"; # Default to cron job

$ant='usc34';	# Not needed for merge as sdtp will substitute merge ant
$band=3;	# Merge telemetry
$mode='merge';	# Merge telemetry

# Set default values for start date, end date and start time to empty strings. If in
# interactive state these are not set then bail out.

$sdate = "";
$edate = "";
$stime = "";

# If there is anything on the command line then this is interactive mode

if($#ARGV != -1) {
    $state = "interactive";
    if(@ARGV) { $sdate  = shift; }
    if(@ARGV) { $edate  = shift; }
    if(@ARGV) { $stime 	= shift; }
    if(@ARGV) { $etime 	= shift; }
    #
    # Further options for re-processing just status or just mission data
    #
    die "No start date" if $sdate eq "";
#    die "No end date"   if $edate eq "";
#    die "No start time" if $stime eq "";
#    die "No end time"   if $etime eq "";
#    $etime = $stime  if $etime eq "";
#    $etime = $stime;
    $pipeline_mission_log = "$pipeline_log/pipeline_mission_log_rescue_$sdate";
    open(LOG, ">> $pipeline_mission_log") || die "Can't open $pipeline_mission_log for writing: $!";
    print LOG "Started (manually) ", scalar(localtime), " (JST)\n";
    print MLOG "manually for $sdate\n";
}
else {
    die "Should not be run by cron yet";
    # Started by cron. Calculate start date, end date and start time
    @today = today();	# @today[0..6] = seconds,minutes,hours,day,month,year,day_of_week (0 = sunday)

    @start_day = other_date(@today,-7);		# Go back 7 days
    @next_day  = other_date(@today,-6);		# Go back 6 days
#    print "start_day = @start_day\n";
#    print "next_day  = @next_day\n";
    $syear  = sprintf "%04u", $start_day[5];	# Get starting year
    $smonth = sprintf "%02u", $start_day[4];	# Get starting month
    $sday   = sprintf "%02u", $start_day[3];	# Get starting day
    $eyear  = sprintf "%04u", $next_day[5];	# Get ending year
    $emonth = sprintf "%02u", $next_day[4];	# Get ending month
    $eday   = sprintf "%02u", $next_day[3];	# Get ending day
    
    $sdate = "$syear$smonth$sday";
    $edate = "$eyear$emonth$eday";
    
#    print "sdate = $sdate\n";
#    print "edate = $edate\n";

    open(LOG, ">> $pipeline_log/pipeline_log_$sdate") || die "Can't open $pipeline_log_$sdate for writing: $!";
    print LOG "Started ", scalar(localtime), " (JST)\n";

    # Get the date of the contact file we will parse to find the start time
    $parse_date = $sdate;

    # If sunday get previous start time and use that for today
    if($today[6] == 0) {	# Sunday
        print LOG "$sdate is Sunday, going back a day\n";
	@yesterday = other_date(@start_day,-1);
	$syear  = sprintf "%04u", $yesterday[5];	# Get starting year
	$smonth = sprintf "%02u", $yesterday[4];	# Get starting month
	$sday   = sprintf "%02u", $yesterday[3];	# Get starting day
	$parse_date = "$syear$smonth$sday";
    }
    
    # Parse contact file to get start time
    $src_file = $parse_date . "_contacts.txt";
    $file = `/bin/ls $pass_list_dir/$src_file`;
    if($file eq "") {
	print LOG "Can't open contact file for $sdate\n";
	pipeline_exit("mission");
    }
    chomp $file;
    print LOG "Using contact file $file for $sdate\n";
    $line = "";
    open(PASS, "< $file") or die "Can't open contacts file\n";
    while(<PASS>) {
	if(/real/) {
	    chomp;
	    $line = $_;
	    last;
	}
    }
    if($line eq "") {
        print LOG "No start time\n";
        pipeline_exit("mission");
    }

    # now get the start time by getting the time 16 characters in from the end of the line
    $stime = substr $line, -16, 4;
    $etime = $stime;
    print MLOG "by cron for $sdate to $edate, start time $stime until $etime\n";
}

# Split the start date into constituent parts
$year  = substr $sdate, 0, 4;
$month = substr $sdate, 4, 2;
$day   = substr $sdate, 6, 2;


############################################### 15 - CLEAN UP

print STDOUT scalar(localtime), " (JST) - Cleaning up\n" if $state eq "interactive";
print LOG "\n", scalar(localtime), " (JST) - Cleaning up\n";

print LOG "\t/bin/rm $temp_idl/*pro\n";
system("/bin/rm $temp_idl/*pro");

print LOG "\t/bin/rm $temp_fits/*\n";
system("/bin/rm $temp_fits/*");

print LOG "\t/bin/rm $temp_plots/*\n";
system("/bin/rm $temp_plots/*");


############################################### 16 - EXIT

pipeline_exit("rescue");

