#!/usr/bin/perl
#
# Process mail from imap server shared folder 'spam' & 'not-spam' through spamassassin sa-learn
# dmz@dmzs.com - March 19, 2004
# http://www.dmzs.com/tools/files/spam.phtml
# LGPL
#
# Things to try if it doesn't work
# 1) Turn debug onto 1 and see if you connect to imap server ad get messages (yes i could have made a command line flag, just didn't see the need once I got it working :)
# 2) Check your local.cf for spamassassin (in debian it's /etc/spamassassin/local.cf) bayes_path settings. 
#
# Also be sure to check that your spamassassin is truely using the bayes files (-D manual startup of spamd to debug there)
#

use Mail::IMAPClient;

my $debug=0;
my $salearn;

my $imap = Mail::IMAPClient->new( Server=> 'imapmailhost:143',
                                  User => 'imapspamuser',
                                  Password => 'imapspamuserpassword',
                                  Debug => $debug);

if (!defined($imap)) { die "IMAP Login Failed"; }

# If debugging, print out the total counts for each mailbox
if ($debug) {
  my $spamcount = $imap->message_count('spam');
  print $spamcount, " Spam to process\n";

  my $nonspamcount = $imap->message_count('not-spam');
  print $nonspamcount, " Notspam to process\n" if $debug;
}

# Process the spam mailbox
$imap->select('spam');
my @msgs = $imap->search("ALL");
for (my $i=0;$i <= $#msgs; $i++)
{
  # I put it into a file for processing, doing it into a perl var & piping through sa-learn just didn't seem to work
  $imap->message_to_file("/tmp/salearn",$msgs[$i]);

  # execute sa-learn w/data
  if ($debug) { $salearn = `/usr/bin/sa-learn -D --no-rebuild --showdots --spam /tmp/salearn`; } 
  else { $salearn = `/usr/bin/sa-learn --no-rebuild --showdots --spam /tmp/salearn`; }
  print "-------\nSpam: ",$salearn,"\n-------\n" if $debug;

  # delete processed message
  $imap->delete_message($msgs[$i]);
  unlink("/tmp/salearn");
}
$imap->expunge();
$imap->close();

# Process the not-spam mailbox
$imap->select('not-spam');
my @msgs = $imap->search("ALL");
for (my $i=0;$i <= $#msgs; $i++)
{
  $imap->message_to_file("/tmp/salearn",$msgs[$i]);
  # execute sa-learn w/data
  if ($debug) { $salearn = `/usr/bin/sa-learn -D --no-rebuild --showdots --ham /tmp/salearn`; }
  else { $salearn = `/usr/bin/sa-learn --no-rebuild --showdots --ham /tmp/salearn`; }
  print "-------\nNotSpam: ",$salearn,"\n-------\n" if $debug;

  # delete processed message
  $imap->delete_message($msgs[$i]);
  unlink("/tmp/salearn");
}
$imap->expunge();
$imap->close();

$imap->logout();

# integrate learned stuff
my $sarebuild = `/usr/bin/sa-learn --rebuild`;
print "-------\nRebuild: ",$sarebuild,"\n-------\n" if $debug;

