#!/usr/bin/perl -w

use strict;
use IO::File;

#options.
use vars qw($test);

sub usage {
  print <<EOF;
rt-allocations.pl [options] filename+
options:
  -t	Test mode.
  -h	This help message.
EOF
  exit 0;
}

while ($ARGV[0] =~ m/^-/) {
  my $arg = shift @ARGV;
  if ($arg eq '-t') {
    # test run.
    $test = 1;
  } elsif ($arg eq '-h') {
    usage();
  } else {
    usage();
  }

}

foreach my $filename (@ARGV) {
  my $fh = new IO::File($filename,'r');
  die "$filename: Input error: $!"
    unless ($fh);

  my @text = $fh->getlines();

  my ($date);
  if (join ('',@text) =~ m/^Minutes of the SIPB Meeting of (.+)$/m) {
    $date = $1;
  } else {
    die "$filename: Couldn't parse date line.";
  }

  my $report;
  my @discussion;
  @discussion = ();
  foreach my $line (@text) {
    if ($line =~ m/^(.+):$/) {
      $report = $1;
    } elsif ($line =~ m/^\t\[(\w+) allocation: (.+)\]$/) {
      print "Sending mail for $2\n";
      sendmessage(<<"EOF");
From: Autogenerated ticket <$1\@mit.edu>
To: rt&treasurer+correspondence\@sipb-rt.mit.edu
Subject: $2

Allocation from the meeting of $date:
@discussion
EOF
    } else {
      if ($line =~ m/\w/) {
	push @discussion, $line;
      } else {
	@discussion = ();
      }
      if ($line =~ m/[\[\]]/) {
	print STDERR "$filename: Possible malformed allocation: $line";
      }
    }
  }
}

sub sendmessage {
  my $message = shift;
  if ($test) {
    open(SENDMAIL, ">&STDOUT");
  } else {
    open(SENDMAIL, "|/usr/lib/sendmail -oi -t -odq")
      or die "Can't fork for sendmail: $!\n";
  }
  print SENDMAIL $message;
  close SENDMAIL;
}
