#! /usr/bin/perl
###############################################################################
#
# $Id: addpat,v 1.1 1997/12/06 00:18:27 bcwhite Exp $
#
# addpat
#
# Add a pattern to a pattern file
#
# Written by: Behan Webster <behanw@pobox.com>
#

use Getopt::Long;

require "SPAMPERL/Email.pl";
require "SPAMPERL/Spam.pl";
require "SPAMPERL/Util.pl";


#
# Help file
#
sub usage {
	$0 =~ m|^.*?([^/]+)$|;
	print "Usage: $1 [--header <header>] [--append <file>] <pattern_filename>\n";
	print "  An email message should be piped into this command.\n";
	print "  It will list any To|Cc|Bcc address not matched by any pattern.\n";
	exit 1;
}

#
# Parse options
#
my %opt;
usage if !GetOptions(\%opt, "append=s", "header=s@");
usage if !@ARGV;
$opt{"header"} = [ "To|Cc|Bcc" ] if !$opt{"header"};

#
# Load pattern files
#
my @patterns = ();
readPatternFiles( \@patterns, @ARGV );

#
# Read in email from STDIN
#
my (%header, $head, $body);
parseEmail(\%header, \$head, \$body);

#
# Find relevant headers/body to search
#
my @search = ();
my $headers = lc "^(Resent-)?(".join("|", @{$opt{"header"}}).")\$";
foreach (keys %header) {
	push(@search, parseAddr($header{$_}) ) if /$headers/;
}

#
# Do the search
#
my ($email, @add);
foreach $email ( uniq(@search) ) {
	push( @add, $email ) if ! search( \@patterns, [$email] );
}

#
# Append to greylist
#
$_ = $opt{"append"};
if( $_ ) {
	open( LIST, ">>$_" ) || die "$_: $!\n";
	select( LIST );
}

if( @add ) {
	$_ = join("\n", @add )."\n";
	print;
	sendEmail(
		"To: $ENV{USER}\n".
		"From: Mail filter <$ENV{USER}>\n".
		"Subject: add addresses to greylist\n",
		"The following addresses have been added to your greylist:\n\n$_" );
}


