#!/usr/local/bin/perl5 -w

###########################################################################
### $Id: //depot/personal/ryan/main/src/wham/cgi-bin/wham.cgi#4 $
###########################################################################
###
###########################################################################

use FindBin '$RealBin';                             # locate libraries
BEGIN { unshift(@INC,"$RealBin/../lib") }

use strict;
use CGI;
use Mail::Field::AddrList;
use wham;

my( $cgi, $cmd, $line, $class, $count, $mid, $whoami, $frm, $f, %config, $blurb);

open(STDERR, ">&STDOUT");
$|=1;
$cgi=new CGI;

chomp($whoami=`whoami`);

### Set up the HTML
print $cgi->header;
print <<EOF ;
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Spam Summary</title>
<style type='text/css'>
th              {       background: #aaaaff;
			color: #000000;
			font-family: Verdana, Arial, Sans Serif;
			font-size: 10pt;
		}
h1		{	font-family: Verdana, Arial, Sans Serif; }
td.border	{	background: #000000;
			color: #00ff00;
		}
td		{	vertical-align: top;}
td.a            {       background: #dddddd;
			color: #000000; }
td.b            {       background: #eeeeee;
			color: #000000;}
A:link          {       color: red }
A:visited       {       color: maroon }
A:active        {       color: blue }
pre,tt		{	font-size: 9pt;}
</style>
</head>
<body>
<center><h1>Spam Summary for $whoami</h1></center>
<center>
EOF

### Quick security check 
$ENV{REMOTE_USER} = "" if( !defined( $ENV{REMOTE_USER}));
if( $whoami ne $ENV{REMOTE_USER}) {
	print "<table cellpadding=0 cellspacing=0 border=0><tr><td class='border'>\n";
	print "<table cellpadding=2 cellspacing=1 border=0><tr><td class='b'>\n";
	print "<font color='#ff0000'>&nbsp;<p>ERROR: you do not appear to have authenticated correctly '$whoami' ne '$ENV{REMOTE_USER}'<p>&nbsp;</font>\n";
	print "</td></tr></table>\n";
	print "</td></tr></table>\n";
# 	exit;
}

%config = &LoadConfig();

### Take care of any deleting or whitelisting
&ProcessSpam() if( defined( $cgi->param('whitelist')) || defined( $cgi->param('blacklist')) || defined( $cgi->param('delete')) || defined($cgi->param('allblack')));

$cmd = "cat $config{spam} | /usr/bin/formail -s ./blurb.pl";
#$cmd = "cat $config{spam} | /usr/bin/formail -s sh -c '/usr/bin/formail -X\"From\" -X\"From:\" -X\"Subject:\" -X\"Message-ID\" ; /usr/bin/formail -I \"\" | head -5'";
open( CMD, "$cmd|") || die "ERROR: could not execute '$cmd'\n";

print "<form method='get' action='wham.cgi'>\n";
print "<table cellpadding=0 cellspacing=0 border=0><tr><td class='border'>\n";
print "<table cellpadding=2 cellspacing=1 border=0>\n";
print "<tr><th>action</th><th>mail summary</th></tr>\n";

for( $count=0;defined( $line = <CMD>);)
{
	if( $line =~ /^From:\s*(.*)/)
	{
		$f = $1;
		if( $count != 0) {
			&PrintBlurb( $count, $frm, $mid, $blurb);
		}
		$blurb = "";
                $count++;
		$frm = $f;

	} elsif( $line =~ /^Message-id:\s*(.*)/) {
		$mid = $1;
	}
	$line =~ s/</\&lt\;/g;
	$line =~ s/>/\&gt\;/g;
	$line =~ s/$/<BR>\n/;
	$line =~ s/^-+(\<BR\>)?//;
	$blurb .= $line;
}
if( $count == 0)
{
	print "<tr><td class='b' colspan=2 nowrap><h3>Congratulations!  You have no spam</h3></td></tr>\n";
} else {
	&PrintBlurb( $count, $frm, $mid, $blurb);
#	print "</td><td class='$class'><input type=checkbox name='whitelist' value='$frm'>whitelist<br><input type=checkbox name='delete' value='$mid'>delete</td></tr>\n";
}

print "</table>\n";
print "</td></tr></table>\n";
print "</form>\n";
print "<input type='submit' value='engage!'>\n" if( $count != 0);
print "<input type='submit' name='allblack' value='blacklist all messages'>\n"
  if( $count != 0);
close( CMD);

if( $? != 0)
{
#	print "ERROR: command failed : $?\n";
#	die "ERROR: command failed : $?\n";
}

###########################################################################
### &PrintBlurb( $class, $from, $mid, $txt);
###########################################################################
###
###########################################################################
sub PrintBlurb
{
	my( $count, $from, $mid, $txt) = @_;

	$class = ($count%2==0) ? "a" : "b";
	print "<tr><td class='$class'><tt>", 
			$cgi->checkbox( -name=>'whitelist', -value=>"$from"),
			"<br>", 
			$cgi->checkbox( -name=>'blacklist', -value=>"$from"),
			"<br>", 
			$cgi->checkbox( -name=>'delete', -value=>"$mid"),
			"<br>", 
			$cgi->hidden( -name=>'id', -value=>"$mid"),
#			$cgi->hidden( -name=>'from', -value=>"$from"),
		"</tt></td><td class='$class'><tt>\n",
		$txt,
		"</td></tr>\n";
}

###########################################################################
### &ProcessSpam();
###########################################################################
### Actually go ahead and delete or whitelist stuff
###########################################################################
sub ProcessSpam
{
	my( $mbox, $addr, $from, $From, $filter, $line);

	print "<table cellpadding=0 cellspacing=0 border=0><tr><td class='border'>\n";
	print "<table cellpadding=2 cellspacing=1 border=0>\n";
	print "<tr><th>by your command</th></tr>\n";
	print "<tr><td class='a'><pre>\n";

	if( defined( $cgi->param('allblack'))) {
	  print "OK ready to nuke everything!\n";
	  ### take each message in the folder (via formail) and
	  ### pipe it through a .procmailrc
	  ### 1st thing will pipe it though add_back -m
	  ### then delete
	  &AllBlack();
	  print "</pre></td></tr>\n";
	  print "</table>\n";
	  print "</td></tr></table><p>\n";
	  return;
	}

	### add the addrs to the whitelist
	if( defined( $cgi->param('whitelist')))
	{
		### Add these entries to the whitelist
#		print "<font color='#ff0000'>", $cgi->param('whitelist'), "<br>\n";
		foreach $from( $cgi->param('whitelist'))
		{
#			print "<font color='#ff0000'>", $from, "<br>\n";
		        $From = Mail::Field->new('From', $from);
			foreach $addr ($From->addresses)
			{
#				print "<font color='#770077'>]]]", $addr, "\n";
				if( defined( $filter = &IsWhite( $addr)))
				{
					print "Address $addr matches <font color='#00ff00'>$filter</font><br>\n";
				} else {
					print "Whitelisting <tt>$addr</tt>\n";
					&AddToList( "white", "added via wham.cgi", $addr);
				}
			}
		}
	}

	### add the addrs to the blacklist
	if( defined( $cgi->param('blacklist')))
	{
		### Add these entries to the whitelist
#		print "<font color='#ff0000'>", $cgi->param('blacklist'), "<br>\n";
		foreach $from( $cgi->param('blacklist'))
		{
#			print "<font color='#ff0000'>", $from, "<br>\n";
		        $From = Mail::Field->new('From', $from);
			foreach $addr ($From->addresses)
			{
#				print "<font color='#770077'>]]]", $addr, "\n";
				if( defined( $filter = &IsBlack( $addr)))
				{
					print "Address $addr matches <font color='#00ff00'>$filter</font><br>\n";
				} else {
					print "Blacklisting <tt>$addr</tt>\n";
					&AddToList( "black", "added via wham.cgi", $addr);
				}
			}
		}
	}


	### Let's create the procmail.rc file that we'll use to
	### filter out messages
	open( PROCRC, ">/tmp/procmailrc.wham.$$");
	print PROCRC <<EOF ;
### Set up a logfile
LOGFILE         = /tmp/procmaillog.wham.$$

:0:
* ^From MAILER-DAEMON
* ^Subject: DON'T DELETE THIS MESSAGE -- FOLDER INTERNAL DATA
$config{spam}

EOF
	### Let's create the procmail.rc file that we'll use to
	### filter out messages
	open( PROCRC, ">/tmp/procmailrc.wham.$$");
	print PROCRC <<EOF ;
### Set up a logfile
LOGFILE         = /tmp/procmaillog.wham.$$

:0:
* ^From MAILER-DAEMON
* ^Subject: DON'T DELETE THIS MESSAGE -- FOLDER INTERNAL DATA
$config{spam}

EOF

	### Add in a section to delete specified message ids
	if( defined( $cgi->param('delete')))
	{
		print PROCRC ":0\n";
		foreach $line ($cgi->param('delete'))
		{
			print "Deleting: $line\n";
                        $line =~ s/\$/\\\$/;
			print PROCRC "* 1^0 ^Message-ID: $line\n";
		}
		print PROCRC "/dev/null\n";
	}

	if( defined( $config{template})) {

		open( TEMPLATE, $config{template}) || die "ERROR: could not open $config{template} : $!\n";
		while( defined( $line = <TEMPLATE>))
		{
			print PROCRC $line;
		}
		close( TEMPLATE);

	} else {

		print PROCRC <<EOF; 
### check for spam
:0:
* ? /home/ryan/src/wham/bin/iswhite
$config{spam}

### If it's not spam, and it's not trash, release it
:0:
$config{release}
EOF
	}

	close( PROCRC);
	rename( $config{spam}, $config{spam} . ".tmp");

	$cmd = "/usr/bin/formail -s /usr/bin/procmail /tmp/procmailrc.wham.$$ < $config{spam}.tmp";
print scalar localtime, "<BR>\n";
	print $cmd;
	open( CMD, "$cmd|") || die "ERROR: could not execute '$cmd' : $!\n";
	while( defined( $line = <CMD>))
	{
		print "$line";
	}
	close( CMD);
print "<BR>\n";
print scalar localtime, "<BR>\n";
	die "ERROR: '$cmd' exited with : $?\n" if( $? != 0);

#	rename( $config{spam} . ".tmp", $config{spam});
	unlink( $config{spam} . ".tmp");
	unlink( "/tmp/procmailrc.wham.$$");
	unlink( "/tmp/procmaillog.wham.$$");

	print "</pre></td></tr>\n";
	print "</table>\n";
	print "</td></tr></table><p>\n";
}


###########################################################################
### &AllBlack();
###########################################################################
### take each message in the folder (via formail) and
### pipe it through a .procmailrc
### 1st thing will pipe it though add_back -m
### then delete
###########################################################################
sub AllBlack() {

  my( $line, $id);

  ### Let's create the procmail.rc file that we'll use to
  ### filter out messages
  open( PROCRC, ">/tmp/procmailrc.wham.$$");
  print PROCRC <<EOF ;
### Set up a logfile
LOGFILE         = /tmp/procmaillog.wham.$$

:0:
* ^From MAILER-DAEMON
* ^Subject: DON'T DELETE THIS MESSAGE -- FOLDER INTERNAL DATA
$config{spam}

EOF

  ### add_black each mail
  print PROCRC ":0c\n";
  foreach $id ($cgi->param('id')) {
    $id =~ s/\$/\\\$/g;
#    print "$id\n";
    print PROCRC "* 1^0 ^Message-ID: $id\n";
  }
  print PROCRC "|/home/ryan/src/wham/bin/add_black -g\n";

  ### delete each mail
  print PROCRC ":0a\n";
  foreach $id ($cgi->param('id')) {
    $id =~ s/\$/\\\$/g;
#    print "$id\n";
    print PROCRC "* 1^0 ^Message-ID: $id\n";
  }
  print PROCRC "/dev/null\n";

  print PROCRC ":0\n";
  print PROCRC "$config{spam}\n";
  close( PROCRC);

  rename( $config{spam}, $config{spam} . ".tmp");
  $cmd = "/usr/bin/formail -s /usr/bin/procmail /tmp/procmailrc.wham.$$ < $config{spam}.tmp";
  print scalar localtime, "<BR>\n";
  print "'", $cmd, "'<BR>\n";
  open( CMD, "$cmd|") || die "ERROR: could not execute '$cmd' : $!\n";
  while( defined( $line = <CMD>)) 	{
    print "$line";
  }
  close( CMD);
  print scalar localtime, "<BR>\n";

  unlink( $config{spam} . ".tmp");
  unlink( "/tmp/procmailrc.wham.$$");
  unlink( "/tmp/procmaillog.wham.$$");
}
