#!/usr/bin/perl -W

#
# PROJECT
#          Hinode/EIS
# PURPOSE
#          Perl script which runs on EISCO. It creates a temporary
#          archive directory, and copies to it the various components
#          of the CP files. This is then tarballed.
# CATEGORY
#          EIS Timeline Planning/Remote Planning
# WRITTEN
#          John Rainnie & David Brooks & David Williams (RPG)
# HISTORY
#          v0.1 JAR 28-OCt-2008
#

#use Date;
use Env qw(HOME SSW CMDPLN);

$a_dir = "$HOME/eis_rp_archive";
#########################################################################
#
# Refresh archive directory
#
#########################################################################
# Check whether $HOME/eis_rp_archive directory exists - remove it if so!
if(-e $a_dir) {
    print "Removing $a_dir\n";
    system("/bin/rm -rf $a_dir");
}

# Re-create the eis_rp_archive directory
system("/bin/mkdir $a_dir");


#########################################################################
#
# Create a new log file in the new archive directory
#
#########################################################################
print "Creating log file: eis_rp_archive/eis_rp_archive_log.txt\n";

open (LOGFILE, ">$a_dir/eis_rp_archive_log.txt");


#########################################################################
#
# CP CMDPLN
#
#########################################################################
system("/bin/mkdir $a_dir/cmdpln");

print LOGFILE "\n";
print "Getting CP (cmdpln) input file updates;\n";
print LOGFILE "Getting CP (cmdpln) input file updates;\n";

print LOGFILE "    $CMDPLN/latest\n";
system("/bin/cp -rL $CMDPLN/latest   $a_dir/cmdpln");
print "    $CMDPLN/latest\n";

print LOGFILE "    $CMDPLN/today\n";
system("/bin/cp -rL $CMDPLN/today    $a_dir/cmdpln");
print "    $CMDPLN/today\n";

print LOGFILE "    $CMDPLN/tomorrow\n";
system("/bin/cp -rL $CMDPLN/tomorrow $a_dir/cmdpln");
print "    $CMDPLN/tomorrow\n";

# Copy next and previous days directories
foreach $day (-5 .. 7) {
    $new_time = time - ($day * (24 * ( 60 * 60)));
    @foo = localtime($new_time);
    $time_string = sprintf "%4u%02u%02u", $foo[5] + 1900, $foo[4] + 1, $foo[3];
    $cmdpln_dir = "$CMDPLN/" . "$time_string";
    if(-e $cmdpln_dir) {
    print "    $cmdpln_dir\n";
    print LOGFILE "    $cmdpln_dir\n";
    system("/bin/cp -rL $cmdpln_dir $a_dir/cmdpln/");
    }
}

print LOGFILE "\n";
print LOGFILE "End of log.\n";
close LOGFILE;

#########################################################################
#
# Tar up the directory here!
#
print "Archiving the necessary files from EISCO needed for remote planning\n";
system("cd $HOME && tar cfz $HOME/eis_rp_archive.tar.gz eis_rp_archive/");
#########################################################################
#
