#!/home/aimpro/utils/perl64/bin/perl -I/home/aimsds/utils/site_perl/lib -I/home/aimpro/utils/perl64/html/site/lib
# send_raa_images.pl
# Author: Bill Barrett

use Mail::Sender;
use Date::Manip;

# The following should be updated on an as needed basis
my $season = "north_2020";
my $version = "01.10";
my $revision = "05";

# If a first argument was specified it should be a date to override the current data
my ($year, $yday, $month, $mday);
my $start_of_string;
if( scalar( @ARGV ) > 0 )
{
    $year = int($ARGV[0] / 1000);
    $yday = $ARGV[0] - ($year * 1000);
    $start_of_string = "Using specified date: $ARGV[0] (yyyyddd)";
} else {  # Get the date from the system
    # Ignore all the variables returned by gmtime other than year and day of year, [5, 7]
    # Definitive data is five days in arrears (86400 seconds per day)
    my $five_day_offset = 5 * 86400;
    ($year, $yday) = (gmtime( time  - $five_day_offset))[5, 7];
    $year += 1900;
    if ($yday == 0)
    {
        $year--;
        if ( ($year % 4) == 0)
        {
            $yday = 366;
        } else {
            $yday = 365;
        }
    }
    $start_of_string = "Getting files for";
}
($month,$mday) = (Date_NthDayOfYear($year,$yday))[1,2];
printf "$start_of_string year: $year day of year: $yday month: $month day of month: $mday\n";

# Get the files to be attached
my $level_2b_path = sprintf("/aim/data/cips/raa_%4d/%02d/level_2b/ver_%s/rev_%s", $year, $month, $version, $revision);
print "$level_2b_path\n";

my $date_year_version = sprintf("%4d\-%03d_v${version}_r${revision}", $year, $yday);
my $level_2b_pattern = "cips_raa_2b_orbit_\\d{5}_${date_year_version}\.(preliminary\.)?png";
print "searching for files matching: $level_2b_pattern\n";

my @png_files;
my $png_file_count;
my $subject = "";

do
{{
    @png_files = ( );
    opendir(DH, $level_2b_path) or die "Couldn't open $level_2b_path for reading: $!";
    while( defined ($file = readdir(DH)) ) {
        next unless $file =~ /$level_2b_pattern/;
        my $filename = "$level_2b_path/$file";
        push(@png_files, $filename);
    }
    closedir(DH);
    $png_file_count = scalar(@png_files);
    print "number of png files matching ${level_2b_pattern}: $png_file_count\n";

    open(MAIL, "|/bin/mailx -t");
    print MAIL "To: james.craft\@lasp.colorado.edu, adrian.gehr\@lasp.colorado.edu\n";
#    print MAIL "To: william.barrett\@lasp.colorado.edu\n";
    if ($png_file_count > 0)
    {
        $subject = sprintf("RAA for %4d-%03d has completed",  $year, $yday);
        print MAIL "Subject: ${subject}.\n\n";
        print MAIL "${subject}. Preparing to send ...\n";
        close(MAIL);
    } else {
        $subject = sprintf("RAA for %4d-%03d has NOT YET completed",  $year, $yday);
        print MAIL "Subject: ${subject}.\n\n";
        print MAIL "${subject}. Waiting for one hour\n";
        close(MAIL);
        sleep(3600);
    }
}} while ($png_file_count <= 0);

# If a second argument was specified it is additional text for the subject and message
my $extra_text = scalar( @ARGV ) > 1 ? $ARGV[1]." " : "";
print "extra text: ${extra_text}\n";
$subject = sprintf("${extra_text}RAA level 2b images for %d-%03d", $year, $yday);
my $from = "aimpi\@lasp.colorado.edu";
my $to = "cora.randall\@lasp.colorado.edu\n";
#my $to = "william.barrett\@lasp.colorado.edu\n";
#my $to = "james.craft\@lasp.colorado.edu, william.barrett\@lasp.colorado.edu\n";
my $cc = "james.craft\@lasp.colorado.edu, lumpe\@cpi.com, adrian.gehr\@lasp.colorado.edu, jcar\@vt.edu\n";
#my $cc = "jvcraft87\@gmail.com, william.barrett\@lasp.colorado.edu";
#my $cc = "james.craft\@lasp.colorado.edu, william.barrett\@lasp.colorado.edu";
#my $cc = "";
$message = sprintf("${extra_text}RAA level 2b for %d-%03d", $year, $yday);

$sender = new Mail::Sender{smtp => 'localhost', from => $from, multipart => 'Mixed', msg => $message, };
$sender->OpenMultipart({
    from => $from, 
    to => $to, 
    cc => $cc,
    subject => $message,
    msg => $message,
    ctype => "text/html",
    encoding => "7bit"
}) or die $Mail::Sender::Error,"\n";

print "Attaching $png_file_count files and sending $message\n";
$sender->Part({
    ctype => 'text/html',
    msg => $message });

foreach (@png_files)
{
    print "Adding $_\n";
    $sender->Attach({
        description => 'aimsds raa png',
        ctype => 'image/png',
        encoding => 'base64',
        disposition => "inline; filename=$_;\r\nContent-ID: <img1>",
        file => $_});
}
printf("Preparing to close and send RAA level 2b images for %d-%03d\n", $year, $yday);

$sender->Close  or die $Mail::Sender::Error,"\n";
exit;

