#!/usr/bin/perl -w

use strict;

use config;

use HTTP::Date;
use IPC::Open2;
use IO::Select;
use IO::Handle;

my @mail;
my $msgid;
my $deldate;
my $flag;
my $score;

$flag = shift;

while(<>) {
	chomp;
	push @mail, $_;

	if (/Message-Id:.*<(.*)>/i) 
	{
		$msgid = $1;
	}

	if (/Delivery-Date: (.*)/i)
	{
		$deldate = HTTP::Date::time2iso(HTTP::Date::str2time(HTTP::Date::parse_date($1)));
	}
}

my $mailstr =  join "\n", @mail;

my $pid = open2(\*R, \*W, "/usr/share/crm114/mailfilter.crm -u $::path 2> /dev/null");
$pid || die "did not work as expected:$!";

my $io = IO::Select->new();
$io->add(\*R);

print W "$mailstr";
close(W);

while (<R>) 
{
	if (/^X-CRM114-Status: .* \( pR: (.*) \)/)
	{	
		$score = $1;
	}
}

if ($flag eq "default")
{
	if ($score < 0)
	{
		#$flag = "spam";
		$flag = "S";
	}
	else
	{
		#$flag = "ham";
		$flag = "H";
	}
}

print $flag . "   " .$score . "\n";

my $dbh = DBI->connect($::dsn, $::db_user_name, $::db_password);

my $sth = $dbh->prepare("SELECT msgid FROM mail WHERE msgid=?");
$sth->execute( $msgid );

if ($sth->rows eq 1)
{
	print "WARNING: message already exists, deleting previous message\n";
	$sth = $dbh->prepare("DELETE FROM mail WHERE msgid=?");
	$sth->execute( $msgid );
}

$sth = $dbh->prepare("INSERT INTO mail (msgid,delivery,body,flag,score) VALUES (?,?,?,?,?)");
$sth->execute( $msgid, $deldate, $mailstr, $flag, $score );
