
# she-bang line removed so webserver leaves this alone
#!/usr/bin/perl -w

use strict;
use Time::HiRes;
use POSIX ":sys_wait_h";

#sub verbose { print "$0: ", @_, "\n" };
sub verbose {}
sub tempfail { exit 75; } # not random; see sysexits.h
my $HOME = "/home/tjs";
my $hostname = "ix";

pipe BOGOIN, TOBOGO or tempfail;
my $child = fork();
if ($child < 0) { tempfail; }
if ($child == 0) {
    verbose "in child";
    close TOBOGO;
    close STDIN;
    if (!open(STDIN, '<&BOGOIN')) {
	print STDERR "can't re-open stdin in child\n";
	exit 3;			# unsure
    }
    exec qw/bogofilter -l -u/;
    exit 3;			# unsure
}
close BOGOIN;

# read standard input
verbose "read msg";
my $msg; { local $/; $msg = <>; }

verbose "writing to bogo...";
print TOBOGO $msg;
close TOBOGO;
if (wait() < 0) {
    verbose "couldn't wait ($!)";
    tempfail;
}
my $ex = $?;
verbose "bogo ex: $?";
if (!WIFEXITED($ex)) {
    verbose "bogofilter did not exit normally";
    tempfail;
}
my $status = WEXITSTATUS($?);
verbose "bogo says $status";
my $folder;
if ($status == 0) { $folder = "INBOX.Spam"; }
elsif ($status == 1) { $folder = "Inbox"; }
elsif ($status == 2) { $folder = "INBOX.Unsure"; }
else { tempfail; }

sub folder_to_dir {
    my $folder = shift;
    if (lc ($folder) eq "inbox") {
	return "$HOME/Maildir";
    } else {
	return "$HOME/Maildir/.$folder";
    }
}
my $base = folder_to_dir($folder);
my @t = Time::HiRes::gettimeofday();
my $rand = rand(999999999);	# violates Maildir guidance; BFD
my $fn = $t[0] . ".P$$"."M$t[1]R$rand.$hostname";
my $tf = "$base/tmp/$fn";
verbose "tempfile=$tf";
if (!open(MSG, ">$tf")) { verbose "can't open temp file\n"; tempfail; }
if (!print MSG $msg) { verbose "can't print msg data"; tempfail; }
close MSG;
my $nf = "$base/new/$fn";
verbose "newfile=$nf";
if (!rename($tf, $nf)) { verbose "can't rename: $!"; tempfail; }
verbose "delivered";
exit 0;
