#!/usr/local/bin/perl

# mailbot.pl -- a simple mailbot program
# By Chris Candreva <chris@westnet.com>
# Stardate 0709.95
#
# This program is now public domain, copy it, change it, do whatever you
# want with it. If you add features, I would like to know about them.
#
# usage: mailbot.pl mailfile
#
# This is usually placed in a sendmail aliases file, such as the following:
#
# support: chris, "|/usr/local/bin/mailbot.pl /home/chris/techmail.txt"
#
# Put any real people who should also receive the mail in front.
# The mailfile should start as follows:
#
# From: A Real Name <username@machine.com>
# Subject: The Subject of the message
# <a blank line>
# Your message starts here, to the end of the file
#
#
# Modifications:  catch and discard anything coming from the
# MAILER-DAEMON.   Tobias Kreidl, Computing Tech. Servicess,
# Northern Arizona University (Tobias.Kreidl@nau.edu) 97-Apr-02

unless ($ARGV[0]) {
	open (OUT,"|/usr/ucb/mail -s 'Error!' postmaster");
	print OUT "There is a misconfigured mailbot. Please fix.\n\n\n";
	close OUT;
	exit 1;
}

$mailfile = $ARGV[0];
$md="";

while(<STDIN>) {
	if (s/^From: //) {
		s/[\012\015]|^ *//g;  #Remove all CR and LF
		# check for MAILER-DAEMON
		/(.*)MAILER-DAEMON?/ && ($md=$1) || /(.*)mailer-daemon?/ && ($md=$1);
		if ($md ne ""){
			# print "Received from MAILER-DAEMON\n"; # debug
			close STDIN; # force I/O to terminate nicely
			exit 0;
		}
		$to = $_;
		open (OUT, "|/usr/lib/sendmail -oi -t");
		open (IN, $mailfile );

		#Read and display FROM line.		
		$_ = <IN>;
		print OUT $_;

		print OUT "To: $to\n";

		while (<IN>) { print OUT $_; }
		close IN;
		close OUT;
	}
}

exit 0;
