#!/usr/bin/env perl

# program_done_e-ping.pl -- Erich Schwarz <emsch@its.caltech.edu>, 1/6/2011.
# Purpose: e-mail pager to tell when a longish program run is done on a server ; e.g., a signal that one is through the velveth part of a velvet assembly.

use strict;
use warnings;
use Mail::Sendmail;
use Getopt::Long;

my %opts = ();

GetOptions ( 'sender=s'  => \$opts{'sender'},
             'target=s'  => \$opts{'target'}, 
             'program=s' => \$opts{'program'},
             'help'      => \$opts{'help'},   );

if ($opts{'help'} or (! $opts{'program'}) ) { 
    die "\n",
        "Format: hack.pl\n",
        '          --program|-p  [name of program whose end will be announced]', "\n",
        '          --sender|-s   [defaults to \'schwarz@redivivus.cacr.caltech.edu\']', "\n",
        '          --target|-t   [defaults to \'schwarz@tenaya.caltech.edu\']', "\n",
        '          --help        [prints this message]', "\n",
        "\n",
        ;
}


$opts{'sender'} |= 'schwarz@redivivus.cacr.caltech.edu';
$opts{'target'} |= 'schwarz@tenaya.caltech.edu';

my $source_machine = $opts{'sender'};
if ( $source_machine =~ /\A.*?@(.+)\z/xms ) { 
    $source_machine = $1;
}

my $date = `date`;
chomp $date;

my %mail = ( To      => $opts{'target'},
             From    => $opts{'sender'},
             Subject => "$opts{'program'} is done on $source_machine",
             Message => "As of $date, $opts{'program'} is done on $source_machine.\n",
);

sendmail(%mail) or die $Mail::Sendmail::error;
print "OK. Log says:\n", $Mail::Sendmail::log;

