use IO::File;

# The number of the filedescriptor that's connected to the socket is
# passed to us on STDIN.

my $filedesc=shift @ARGV;

my $socket=new IO::File "+<&$filedesc";

die "$!" unless defined $socket;

my $line;
my $first=1;
my $errmsg="200 Ok";

#
# Read lines from the socket.  Each line contains a filename.  An empty line
# terminates the list.  The first line is the filename of the datafile
# containing the message text.  The subsequent lines are filename(s) of
# control files.
#

while (defined ($line=<$socket>))
{
my $msg;

	chomp $line;
	last unless $line;

	if ($first)
	{
		$msg=filterdata($line);
	}
	else
	{
		$msg=filtercontrol($line);
	}
	$first=0;
	$errmsg=$msg if $msg;
}

$errmsg .= "\n" unless $errmsg =~ /\n$/;
print $socket $errmsg;

$socket->close;

sub filterdata()
{
my $filename=shift;

#  Here's where the custom content filter is implemented.  Use filehandles
#  so that cleanup's automatic.

my $fh=new IO::File "< $filename";
	return "" unless defined $fh;

my $line;
my $i=0;
my $time=time();
my $fname="$time.$$.babylon.mns.ru,$i";

	while(-e $fname){
	    $i++;
    	    $fname="$time.$$.babylon.mns.ru,$i";
	}
	
	open(FCC,">/home/courier/Maildir/new/$fname") or return "500 Can't filter message (fname=$fname)";
	while ( defined ($line=<$fh>)){
	    print FCC $line;
            if($line=~/futurumtour\@mailru.com/i){
	        return "550 Spammers go away !!!";
	    }
	}
	close(FCC);

	return "";
}

sub filtercontrol()
{
my $filename=shift;
#my $firstline;
#
#    open(F,$filename) or return "500 Can't open control file";
#    $firstline=<F>;
#    close(F);
#    chomp($firstline);
#    $firstline=substr($firstline,1,40);
#
#    if($firstline eq "futurumtour\@mailru.com"){
#	return "550 Spammers are not welcome here !";
#    }else{
#	return "";
#    }
}
