#!/usr/bin/perl
# ispy
# ...with my eye... an email...
# Reads /etc/ispy/watchfile
# Gets email from stdin.
#
# See http://www.geocities.com/im_reading_your_email for documentation
# and updated versions.

use MIME::Entity;

if (open(WATCHED, "/etc/ispy/watchfile")) {
	@watched = <WATCHED>;
	close WATCHED;
}
chomp @watched;

@headers = ();
@headers2 = ();
@body = ();
@msg = ();

# Grab headers into a giant array
while (<STDIN>) 
{
	last if /^$/;
	push @headers, $_;
	if (/^Subject:/) { $mailsubject = $_; }
	if (/^To:/) { $mailto = $_; }
}

$mailsubject =~ s/^Subject:.(.*)/$1/g;
$mailto =~ s/^To:.*<(.*)>/$1/g;

@headers2 = @headers;

while (<STDIN>)
{
	push @body, $_;
}

for (@watched) {
	# 0 = address or file
	# 1 = regex
	@watch = split;
	$regex = $watch[1];
	if ($regex =~ /^$/) { next; }
	foreach (@headers) {
		if (/$regex/) {
			# send via email
			if ($watch[0] =~ /^[a-zA-Z0-9].*/) {
				for (@headers2) {
					$msg .= $_;
				}
				$msg .= "\n";
				for (@body) {
					$msg .= $_;
				}
				$mimesubject = "[" . $mailto . "] " . $mailsubject;
				$mimemsg = MIME::Entity->build(Type => "message/rfc822",
					From   => "messenger",
					To     => $watch[0],
					Subject=> $mimesubject,
					Data   => $msg);
				open MAIL, "| /usr/sbin/sendmail -t -oi -oem";
				$mimemsg->print(\*MAIL);
				close MAIL;
			# append to a file
			} elsif ($watch[0] =~ /\/.*/) {
				$to = ">>" . $watch[0];
				open (OUT, $to) or last;
				# mbox header
				print OUT "From ispy ", scalar(gmtime), "\n";
				for (@headers2) {
					print OUT $_;
				}
				# Blank line separates header/body
				print OUT "\n";
				for (@body) {
					print OUT $_;
				}
				# mbox compatibility
				print OUT "\n";
				close OUT;
			}
			last;
		}
	}
}
