#!/usr/bin/perl
#
# Mailparser.pl
# Author: Eric Bambach
# Email: eric@cisu.net
# Date:	9/14/07
#
# Several years ago I wrote a C program that looks for the string 
# X-Spam-Flag: Yes and pipes to /dev/null but lately people have been
# reporting it partially eats their mail (and I haven't been able to 
# reproduce the bug).
# 
# This program mimics the C programs original behvior and looks for that
# flag in the first MAXLINES. If it finds it, it silently eats the
# message. If its not spam then it writes the full contents to STDOUT
#
# Note that memory usage is tied to MAXLINES since it has to buffer that
# amount. Also, if maxlines is too low than the flag may not be found
#
#
use strict;
use warnings;

my $VERSION = 1.0;

#Configurable
my $MAXLINES = 512;
my $PATTERN = qr /^X-Spam-Flag: YES/;

my $i = 0;
my @buffer;
my $found = 0;

while(<>){
	next if ($found);
	if( $i < $MAXLINES && m/$PATTERN/){
		$found = 1;
		next;
	}elsif($i > $MAXLINES){
		while(scalar @buffer > 0){
			print shift @buffer;
		}
		print;
	}else{
		push(@buffer,$_);
	}
	$i++;
}

#If the message is less than MAXLINES we still need to print it
#
if(!$found){
	while(scalar @buffer > 0){
		print shift @buffer;
	}
}

exit 0;
