#! /usr/bin/perl
###############################################################################
#
# $Id: chkmail,v 1.1 1997/12/06 00:18:27 bcwhite Exp $
#
# chkmail
#
# Check for a pattern in an email message
#
# 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>] [--body] <pattern_filename>\n";
	print "  An email message should be piped into this command.\n";
	print "  It will return 0 if any of the patterns in the pattern\n";
	print "  file match the specified headers or body.\n";
	exit 1;
}

#
# Parse options
#
my %opt;
usage if !GetOptions(\%opt, "body", "header=s@", "verbose");
usage if !@ARGV;
$opt{"header"} = [ "From|Sender" ] 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 $headers = lc "^(Resent-)?(".join("|", @{$opt{"header"}}).")\$";
my @search = ();
push(@search, $body) if $opt{"body"};
foreach (keys %header) {
	push(@search, $header{$_}) if /$headers/;
}

#
# Do the search
#
$_ = search(\@patterns, \@search);		# Search for pattern
slurp( \$buffer );						# Read in rest of STDIN
if( $_ ) {
	print "Matched: $_\n" if $opt{"verbose"};
	exit 0;
} else {
	print "No matches.\n" if $opt{"verbose"};
	exit 1;
}
