#!/usr/bin/perl 
#
#Author: Phillip Hofmeister
#Purpose: Strip IMAP/POP Daemon generated emails out of mailbox

use strict;

sub checkheader(@);

my $print;
my $inheader;
my @header;

foreach my $line (<>) {
	if ($line =~ /^From (.*)/i) {
	  	$inheader = 1;
		$print = 0;
		@header = ();
	}
	if (($line =~ /^$/) && ($inheader)) {
		$inheader = 0;
		push (@header, $line);
		$print = checkheader(\@header);
	}
	if ($inheader) {
		push(@header, $line);
	}
	print $line if $print;
}

sub checkheader(@) {
	my $printmail;
	my $aref = shift;
	if (($$aref[0] =~ /^From MAILER-DAEMON/) && ($$aref[3] =~ /Subject: DON'T DELETE THIS MESSAGE/)) {
		$printmail = 0;
	}
	else {
		$printmail = 1;
	}

	if ($printmail) {
		foreach my $headline (@$aref) {
			print $headline;
		}
	}
	return $printmail;
}
