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

###########################################################################
### $Id: //depot/personal/ryan/main/src/wham/bin/isspam#5 $
###########################################################################
###
###########################################################################
my( $BINDIR, $LIBDIR, $CGIDIR);

use FindBin '$RealBin';                             # locate libraries
use vars qw($BINDIR $LIBDIR $CGIDIR $CONFDIR);

BEGIN {
$BINDIR="$RealBin/../bin";
$LIBDIR="$RealBin/../lib";
$CGIDIR="$RealBin/../cgi-bin";
$CONFDIR="$RealBin/../etc";
}

use lib "$LIBDIR";
use strict;
use Getopt::Long;
use wham;

my( %argv, $line, %config, $filter, %headers, @WHITE, @BLACK);

### Get options
if( !(GetOptions( \%argv, "c|config=s", "v|verbose", "h|help",)) || defined($argv{h})) {
	print STDERR "Usage: spammail [options]\n";
	exit 0;
}

### Where is the config file
%config = &LoadConfig($argv{c});

### Load in the black and white lists
@BLACK = &ReadList( $config{black});
@WHITE = &ReadList( $config{white});

### Parse the mail
%headers = &ProcessHeaders();

print STDERR "INFO from: $headers{from}\n";
print STDERR "INFO subj:  $headers{subject}\n" if( defined( $headers{subject}));

### Anything that matches BLACK filters is un-trusted
foreach $filter (@BLACK)
{
	print "INFO =~ black '$filter'\n" if( defined( $argv{"v"}));
	if( $headers{from} =~ /$filter/i) {
		print STDERR "INFO matches BLACK -- '$filter'\n";
		exit 0;
	}
}

### Anything that matches WHITE filters is trusted
foreach $filter (@WHITE)
{
	print STDERR "INFO =~ white '$filter'\n" if( defined( $argv{"v"}));
	if( $headers{from} =~ /$filter/i) {
		print STDERR "INFO matches WHITE -- '$filter'\n";
		exit 1;
	}
}

print STDERR "INFO untrusted $headers{from}\n";
exit 0;

###########################################################################
### ProcessHeaders of an email
###########################################################################
sub ProcessHeaders
{
	my( $boundary, $type, $mid);
	my( $from, $subj, %HEADER);

	$type = "";
	$boundary = "";

	### First we need to read through the mail headers to 
	### extract the boundary delimiter, as well as the Content-type
	### (We only deal with some messages
	while( defined( $line =<>))
	{
		### end of headers
		last if( $line =~ /^\s*$/);

		if( $line =~ /^([^: 	]+):/)
		{
			$type = $1;
#			print STDERR "tyep: $type\n";
		}
		if( $line =~ /^Message-Id: <?([^>]+)>?/i)
		{
			$mid = $1;
		}
		if( $type =~ /Content-Type/i)
		{
			if( $line =~ /boundary="?([^";]+)"?/i)
			{
				$boundary = $1;
				chomp( $boundary);
			}
		} elsif( $type =~ /^From/i) {
			if( $line =~ /^(From:)?\s*(.*)/i)
			{
				$HEADER{from} = "$2";
			}
		} elsif( $type =~ /Subject/i) {
			if( $line =~ /^(Subject:)?\s*(.*)/i)
			{
				$HEADER{subject} = "$2";
			}
		}
#		print $line;
	}
	return( %HEADER);
}
