#! perl -w

#Usage:
#  /afs/sipb/project/outland/bin/tzc -o -s | perl zephyr-mail.pl

use IO::Handle; # for "flush STDOUT"

# export PERL5LIB=/mit/perl-lib/modules
require Mail::Send;

# Suggestion:
#
# Use Gmail's "plus-addressing" (plus a gmail filter to add a label).

#$mailto='<yourgmail+zephyr@gmail.com>';
#$mailfrom_email='<yourname@mit.edu>';

die '$mailto is undefined' unless defined $mailto;
die '$mailfrom_email is undefined' unless defined $mailfrom_email;

while (<>) {
  #ignore TZC preamble
  last unless /^;/;
}

# now at the first blank line
$m="";
while (<>) {
  $m.=$_;
  #message separators
  if (/\)\x00$/) {
    $m=~s/^\x01//;
    $m =~ s/\x00$//;
    undef $class;
    if ($m =~ /\(class\s+\.\s+(.+?)\)/i) {
      $class=lc $1;
    }
    undef $inst;
    if ($m =~ /\(instance\s+\.\s+(.+?)\)/i) {
      $inst=lc$1;
      $inst =~ s/^\"//;
      $inst =~ s/"$//;
    }
    undef $sender;
    if ($m =~ /\(sender\s+\.\s+(.+?)\)/i) {
      $sender=$1;
      $sender =~ s/^\"//;
      $sender =~ s/"$//;
    }
    if (defined $class and defined $inst and defined $sender) {
      $m =~ s/\) \(/\)\n\(/g;
      $m =~ s/" "/" "\n/g;
      print "CLASS: $class\nINSTA: $inst\nSENDE: $sender\n$m\n";
      $msg = new Mail::Send Subject=>"class $class instance $inst", 
        To=>$mailto;
      $msg->set("From", ("\"$sender\"". $mailfrom_email));
      $fh = $msg->open;               # some default mailer
      print $fh "$m";
      $fh->close;
    } else {
      print "MESSAGE\n$m/MESSAGE\n";
    }
    flush STDOUT;
    $m="";
  }
}
