#!/usr/bin/perl

@listing = `ls -1 /etc/mail/spamassassin/*.cf`;

foreach $file (@listing) {
	chomp $file;
	my $shortfile = $file;
	$shortfile =~ s/^.+\/([^\/]+)$/$1/;
	next if $shortfile eq 'local.cf';
	my @foo = `grep -i '^score' $file | awk '{print \$2}' | sort | uniq`;
	foreach (@foo) {
		chomp;
		$rulefile{$_} = $shortfile;
		$filecount{$shortfile} = 0;
	}		
}

undef @listing;

@listing = `ls -1 /usr/share/spamassassin/*.cf`;

foreach $file (@listing) {
	chomp $file;
	my $shortfile = $file;
	$shortfile =~ s/^.+\/([^\/]+)$/$1/;
	next if $shortfile eq 'local.cf';
	my @foo = `grep -i '^describe' $file | awk '{print \$2}' | sort | uniq`;
	foreach (@foo) {
		chomp;
		$rulefile{$_} = $shortfile;
		$filecount{$shortfile} = 0;
	}		
}

my(%rulescore,%madediff);
foreach my $search (('/usr/share/spamassassin/*.cf','/etc/mail/spamassassin/*.cf')) {
	open(BLAH, "/bin/grep -hi '^score' $search|");
	while(<BLAH>) {
		chomp;
		s/\t/ /g;
		s/ +/ /g;
		s/^ +//g;
		s/ +$//g;
		s/score +//i;
		my @blah = split ' ';
		if(@blah == 5) {
			$rulescore{$blah[0]} = $blah[4];
			$madediff{$blah[0]} = 0;
		} else {
			$rulescore{$blah[0]} = $blah[1];
			$madediff{$blah[0]} = 0;
		}
	}
	close(BLAH);
}

open(BLAH, "/bin/grep 'spamd: result:' /var/log/maillog|");
my $spamcount = 0;
while(<BLAH>) {
	chomp;
	my($msgscore,$required);
	next if /user=bb,/;
	if(/result: Y (.+?) /) {
		$msgscore = $1;
		$spamcount++;
	} else {
		next;
	}
	if(/required_score=(.+?),/) {
		$required = $1;
	} else {
		$required = 5;
	}
	if(/ - (.+?) scantime=/) {
		my $matches = $1;
		my @rules = split ',',$matches;
		foreach (@rules) {
			next unless $rulescore{$_};
			if(($msgscore - $rulescore{$_}) < $required) {
				$madediff{$_}++;
			}
		}
	}
}
close(BLAH);

for(my $i=1;$i<=7;$i++) {
	open(BLAH, "/usr/bin/zgrep 'spamd: result:' /var/log/maillog.$i.gz|");
	my $spamcount = 0;
	while(<BLAH>) {
		chomp;
		my($msgscore,$required);
		next if /user=bb,/;
		if(/result: Y (.+?) /) {
			$msgscore = $1;
			$spamcount++;
		} else {
			next;
		}
		if(/required_score=(.+?),/) {
			$required = $1;
		} else {
			$required = 5;
		}
		if(/ - (.+?) scantime=/) {
			my $matches = $1;
			my @rules = split ',',$matches;
			foreach (@rules) {
				next unless $rulescore{$_};
				if(($msgscore - $rulescore{$_}) < $required) {
					$madediff{$_}++;
				}
			}
		}
	}
	close(BLAH);
}

my %filediff;
print "spamcount: $spamcount\n\n";
foreach(sort keys %madediff) {
	next unless $madediff{$_} > 0;
	print "$_ $madediff{$_}\n";
	$filediff{$rulefile{$_}}++;
}
print "\n\n";

foreach(sort keys %filediff) {
	print "$_ $filediff{$_}\n";
}
