#!/usr/local/bin/perl

#sends the mail messages generated by other scripts

my $TEST = 0;
my $SENDMAIL = 0;

if ($ARGV[0] eq "-s") {
    print "sending mail\n";
    $SENDMAIL = 1;
    shift @ARGV;
}

if ($TEST) {
    $filename = "sendmail.test";
} else {
    $filename = $ARGV[0];
    if (!$filename) {
	print "Enter mail file: ";
	$filename = <STDIN>;
	chomp $filename;
	print "$filename\n";
    }
}

if (-e $filename) {
    print "Opening $filename\n";
    open MAILFILE, $filename;
} else {
    print "$filename does not exist\n";
    exit(0);
}

if (!$SENDMAIL && -e "$filename.mail") {
    print "Removing $filename.mail\n";
    print `rm $filename.mail`;
}

process_mail($filename);

close MAILFILE;

sub process_mail {
    my $msg = "";
    $sendmail = "/usr/sbin/sendmail -t -n -oi";
    while (<MAILFILE>) {
	if (/^From:/ && $msg) {
	    send_message($msg);
	    $msg = $_;
	} else {
	    $msg .= $_;
	}
    }
    send_message($msg);
}

sub send_message {
    my ($msg) = @_;
    if ($msg) {
	if ($SENDMAIL) {
	    open(MAIL,"| $sendmail");
	} else {
	    open MAIL, ">>$filename.mail";
	}
	print MAIL $msg;
	print MAIL "----------------------------\n";
	close(MAIL);
    }
}







