#! /usr/bin/perl

# use like so:
#
# grep "reject: body" /var/log/mail.log | whichrule.pl | less
# or
# grep "reject: header" /var/log/mail.log | whichrule.pl | less

# hard-coded for now.  should extract from postconf
$bcfile = '/etc/postfix/body_checks' ;
$hcfile = '/etc/postfix/header_checks' ;

open(BC,"<$bcfile") || die "couldn't open $bcfile: $!";
while(<BC>) {
	chomp ;
	s/^#.*//;

	s/^\///;
	s/\/\s*REJECT\s*$//;

	s/^\s*|\s*$//;

	next if (/^$/) ;

	push @body, $_;
};
close(BC);
$brules = (@body - 1);

open(HC,"<$hcfile") || die "couldn't open $hcfile: $!";
while(<HC>) {
	chomp ;
	s/^#.*//;

	s/^\s*\///;
	s/\/\s*REJECT\s*$//;

	s/^\s*|\s*$//;

	next if (/^$/) ;

	push @header, $_;
};
close(HC);
$hrules = (@header - 1);

while (<>) {
	chomp ;
	m/.*(?:reject|discard|hold): (body|header) (.*) from .*; \w+=/;
	my ($bh,$text) = ($1,$2);
	print "\n------\n$_\n$bh\n$text\n\n" ;
	if ($text eq '') {print "BUG!!!\n" ; next}; 

	if ($bh eq 'body') {
		foreach my $i (0..$brules) {
			next unless ($text =~ /$body[$i]/i) ; 		
			print "$i: '$body[$i]'\n" ;
			my $t = $text ; $t =~ s/.*($body[$i]).*/$1/;
			print "\n$t\n\n";

		} ;
	} elsif ($bh eq 'header') {
		foreach my $i (0..$hrules) {
			next unless ($text =~ /$header[$i]/i) ; 		
			print "$i: '$header[$i]'\n" ;
			my $t = $text ; $t =~ s/.*($header[$i]).*/$1/;
			print "\n$t\n\n";
		}
	}
}

