#!/usr/bin/perl  -w
# (c)Copyright 2002 Stephen Samuel.
# Permission to copy under the terms of the GNU public license version 2.0
# see http://www.gnu.org/licenses/licenses.html#GPL for more details
#
# $Header: /home/samuel/bin/spam/RCS/peelhead,v 1.3 2002/09/24 21:18:25 samuel Exp samuel $
# $Log: peelhead,v $
# Revision 1.3  2002/09/24 21:18:25  samuel
# generally cleaned up and working.
#
# Revision 1.2  2002/09/24 20:52:43  samuel
# Mostly working good... now to clean up a bit.
#
# Revision 1.1  2002/09/24 18:50:59  samuel
# Initial revision
#
#


# open HEADDUMP,"/tmp/headdump";
my( $ThisNull, $InHead,$LastNull, $RecPrinted,$Header);
my ( $hostname , $hostaddr) ;

# My_MX should match the IP address of any machines that are secondary MX
# or that you fetchmal from
$My_MX="199.185.220.245|127.0.0.1";

# My_POP should match machines that you fetchmail from that don't 
# match My_MX properly
$My_POP="mail.telus(planet)?.net";

# Check_MX is used for sanity checking.
# The names of machines that actually accept the mail  ($j for sendmail)
# (before POPping) should be here.  set to "." to disable
# (This is the 'Recieved: .*  by $Check_MX )
# I.E. the names that your MX machines know themselves to be.

$check_MX ="priv-edtn|me.bcgreen.com|budoshin.zoku.net|"
	."h24-68-93-250.vc.shawcable.net|localhost.localdomain|"
	."\\w+.bc.hsia.telus.net|me.bcgreen.com|me1.bcgreen.com";

$RecPrinted=1;
$LastNull=1;
while(<>){
	$ThisNull=0;
	chomp;
	if(/^$/){
		$ThisNull=1;
		if($InHead){
			$InHead=0;
			process_line($headerline);
			$headerline="";
			# print"__________________\n\n"; # separator?
			if (! $RecPrinted ){
				# print HEADDUMP "\n\n$Header";
				print "OOPS\n";
			}
			$RecPrinted=0;
			# $Header="";
		};
	}elsif($LastNull && /^From /){
		# Start of header
		$InHead=1;
		$headerline=$_;
	}
	
	if($InHead){
		if(s/^\s+/ /){
			$headerline .= $_;
		}else{
			process_line($headerline) if ($headerline =~ /./);
			$headerline=$_;
		}
	};
	
	$LastNull=$ThisNull;
};

sub process_line{
	local ( $_);
	$_=$_[0];

	# $Header .=$_;
	# print "\$_='$_'\n";
	if(/^Received: from /){
		if(/\[($My_MX)\]/ || /Received: from ($My_POP)\s.* with POP3 \(fetch/){
			# skip...
		}elsif($RecPrinted){
		 # already printed line for this msg.

		}elsif(/\(([^[]*)\[([\d.]+)\]( .may be forged.)?\)( +by ($check_MX ).*)?\s*$/){
			( $hostname , $hostaddr) = ($1, $2);
			 print "$hostaddr $hostname\n";
			#   split to class B
			#   ($hostaddr =~ /(^\d+\.\d+\.\d+)/) || print "_____ $_" ;
			#   print "$1\n";
			$RecPrinted=1;
		}else{
			print "++$_\n";
		}

	}elsif(/Received: \(from .*\@localhost\)[^]]*$/){
		# skip
	}elsif(/^Received:/){
		print STDERR "_*_*_* $_\n" if ! $RecPrinted;
	};
		#print STDERR "_*_*_*($RecPrinted) $_\n" if  / 21 Aug 2002 20:28:18/;

	
}
