#!/home/aimpro/utils/perl64/bin/perl -I/home/aimsds/utils/site/lib -I/home/aimpro/utils/perl64/html/site/lib

use Mail::Sender;

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

# If a first argument was specified it should be a date to override the current data
my ($year, $yday);
if( scalar( @ARGV ) > 0 )
{
    $year = int($ARGV[0] / 1000);
    $yday = $ARGV[0] - ($year * 1000);
    print "Using specified date: $ARGV[0] (yyyyddd) year: $year day of year: $yday\n";
} 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;
        }
    }
    printf "Getting files for: year: %4d day of year: %3d\n", $year, $yday;
}

# If a second argument was specified it is additional text for the subject and message
my $extra_text = scalar( @ARGV ) > 1 ? $ARGV[1]." " : "";
my $subject = sprintf("${extra_text}Definitive daisy for %d-%03d", $year, $yday);

my $path = "/aim/data/cips/$season";
my $version_revison = "ver_${version}/rev_${revision}";
my $level_3_path = sprintf("$path/level_3/${version_revison}");
my $level_2_path = $level_3_path;
$level_2_path =~ tr/level_3/level_2/;
print "level 3 path: ${level_3_path}\n";
print "level 2 path: ${level_2_path}\n";

my $date_year_version = sprintf("%4d\-%03d_v${version}_r${revision}", $year, $yday);
my $level_3_pattern = "cips_sci_3a_${date_year_version}(_prelim)?\.(preliminary\.)?png";
my $level_2_pattern = "cips_sci_2_orbit_\\d{5}_${date_year_version}_[a-z]{3}(_prelim)?\.(preliminary\.)?png";

my @png_files;
my $png_file_count;

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

    open(MAIL, "|/bin/mailx -t");
    print MAIL "To: james.craft\@lasp.colorado.edu, william.barrett\@lasp.colorado.edu\n";
#    print MAIL "To: william.barrett\@lasp.colorado.edu\n";
    print MAIL "From: aimpi\@lasp.colorado.edu\n";
    
    if ($png_file_count > 0)
    {
        $subject = sprintf("Definitive daisy 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("Definitive daisy 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);
        print "${subject}. Waiting for one hour\n";
        sleep(3600);
    }
}} while ($png_file_count <= 0);

@level_2_files = ( );
opendir(DH, $level_2_path) or die "Couldn't open $level_2_path for reading: $!";
while( defined ($file = readdir(DH)) ) {
    print "$file\n";
    next unless $file =~ /$level_2_pattern/;
    print "match ${file}\n";
    my $filename = "$level_2_path/$file";
    push(@level_2_files, $filename);
}
closedir(DH);
push(@png_files, @level_2_files);
$png_file_count = scalar(@png_files);

print "Adding $png_file_count attachments\n";

my $message = "${subject}";
my $from = "aimpi\@lasp.colorado.edu";
#my $to = "william.barrett\@lasp.colorado.edu\n";
my $to = "cora.randall\@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";
#my $cc = "william.barrett\@lasp.colorado.edu\n";

$sender = new Mail::Sender{smtp => 'localhost', from => $from,multipart => 'Mixed', msg => $message, };
$sender->OpenMultipart({
    from => $from, 
    to => $to, 
    cc => $cc,
    subject => $subject,
    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 daisy png',
    ctype => 'image/png',
    encoding => 'base64',
    disposition => "inline; filename=$_;\r\nContent-ID: <img1>",
    file => $_});
}
printf("Preparing to close and send Definitive daisy for %d-%03d\n", $year, $yday);

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

