#!/usr/bin/perl

# You'll need to set up a .forward file that feeds your mail to this script.
# Mine looks like this:
#   "| /a/lwall/bin/mailagent /a/lwall lwall Larry >>/usr/spool/mail/lwall 2>&1"
# Actually, this doesn't work real good, since I don't lock the mail file.
# Someday I'll fix this.  For now, put something like
#   lwall, "| /a/lwall/bin/mailagent /a/lwall lwall Larry >>/a/lwall/.bak 2>&1"

($HOME, $USER, $NAME) = @ARGV;

$ENV{'PATH'}="$1:/bin:/usr/bin:/usr/ucb";
$ENV{'IFS'} = '' if $ENV{'IFS'};

$hostname = `hostname`;

exec '/bin/cat' unless $NAME;
exec '/bin/cat' unless chdir $HOME;
exec '/bin/cat' unless $hostname =~ /vax/;

$HOME=`pwd`;
chop($HOME);
$ENV{'HOME'} = $HOME;
$ENV{'USER'} = $USER;
$ENV{'NAME'} = $NAME;

umask(022);

if (open(commands,".commands")) {
    while (<commands>) {
	chop;
	$command{$_} = 1;
    }
    close(commands);
}

$dest = $USER;
$cmd = "set -x\n";
line: while (<stdin>) {
    $all .= $_;
    s/^From ([^ 	]*).*$/$1/ && ($dest = $1);
    /@RR/ && ($ack = 1);
    if (1 .. /^$/) {
	if (/^Apparently-To:.*admin/) { $admin = 1; }
	if (/^To:.*admin/) { $admin = 1; }
	if (/^Cc:.*admin/) { $admin = 1; }
    }
    if (/^Subject:[ \t]*(.*)/) { $subj = $1; }
    if (/^Title:[ \t]*(.*)/) { $subj = $1; }
    if (/^Subject:[ 	]*[Cc]ommand[ 	]*$/ .. 99) {
	s/^	@SH/@SH/;
	if (/^@SH/) {
	    s/\\!/!/g;
	    if (/[=$^&*([{}`\\|;>?]/) {
		s/^@SH/bad cmd:/;
		$bad .= $_;
		next line;
	    }
	    s/ PATH/ $dest/;
	    s/SH mailpath/SH mailpatch/;
	    s/@SH[ 	]*//;
	    if (/^([^ \t]+)[ \t]/) {
		$first = $1;
	    }
	    else {
		$first = $_;
		chop($first);
	    }
	    if (!$command{$first}) {
		s/^/unk cmd: /;
		$bad .= $_;
		next line;
	    }
	    $cmd .= $_;
	}
    }
}

if ($dest ne $USER) {

    if ($cmd ne "set -x\n") {
	open(cmd,">/tmp/mess.cmd$$");
	print cmd $cmd;
	close cmd;
	$tmp = `sh -x /tmp/mess.cmd$$ 2>&1`;
	if ($?) {
	    open(mailer,"|/bin/mail $dest $USER");
	    print mailer
"Subject: the following returned a non-zero status
To: $dest

$tmp

mailagent speaking for $USER
";
	    close mailer;
	}
	unlink "/tmp/mess.cmd$$";
    }

    if ($ack) {
	open(mailer,"|/bin/mail $dest $USER");
	print mailer
"Subject: $subj
To: $dest

Here is the receipt you requested.

mailagent speaking for $USER
";
	close mailer;
    }

    if ($bad) {
	open(mailer,"|/bin/mail $dest $USER");
	print mailer
"Subject: the following commands were not executed
To: $dest

$bad

If $NAME can figure out what you wanted he may do it anyway.

mailagent speaking for $USER
";
	close mailer;
    }
}

if ($admin) {
    open(out,">>.junk");
    select(out);
}

print $all,"\n\n";

