#!/usr/bin/perl

use Mail::SpamAssassin;
use Mail::IMAPClient;
use strict;
use warnings;

my $mailhost = 'mail.hostname.tld';
my $mailuser = 'username';
my $mailpass = 'password';
my $spamfolder = 'Public Folders/_SPAM';
my $hamfolder = 'Public Folders/_HAM';
my $spamuser = 'nobody';
my $debug = 0;
my $purge = 1;

# Connect to IMAP.
my $imap = Mail::IMAPClient->new( Server=> $mailhost,
                                  User => $mailuser,
                                  Password => $mailpass);

# Connect to SpamAssassin and init learner.
my $spamassassin = Mail::SpamAssassin->new({username => $spamuser, debug => $debug});
$spamassassin->init_learner();

my @msgs; my $imapmail; my $samail; my $status; my $learned;

# Process the spam mailbox.
$imap->select($spamfolder);
@msgs = $imap->search("ALL");

# Process each message, one at a time.
foreach(@msgs) {
	# Get message.
	$imapmail = $imap->fetch("$_ (RFC822)");
	if($purge == 1) {
		$imap->delete_message($_);
	}
	
	# Perform learning.
	$samail = $spamassassin->parse($imapmail, 1);
	$status = $spamassassin->learn($samail, undef, 1, 0);
	$learned = $status->did_learn();

	# Verify learning.
	if (!defined $learned) {    # undef=learning unavailable
		die "ERROR: the Bayes learn function returned an error.\n";
	}
	elsif ($learned == 1 && $debug == 1) {   # 1=message was learned.  0=message wasn't learned
		print "Message learned.\n";
	}
	elsif ($learned == 0 && $debug == 1) {
		print "Message not learned.\n";
	}
}

# Purge.
$imap->expunge();
$imap->close();

# Process the ham mailbox.
$imap->select($hamfolder);
@msgs = $imap->search("ALL");

# Process each message, one at a time.
foreach(@msgs) {
        # Get message.
        $imapmail = $imap->fetch("$_ (RFC822)");
	if($purge == 1) {
		$imap->delete_message($_);
	}

        # Perform learning.
        $samail = $spamassassin->parse($imapmail, 1);
        $status = $spamassassin->learn($samail, undef, 0, 0);
        $learned = $status->did_learn();

        # Verify learning.
        if (!defined $learned) {    # undef=learning unavailable
                die "ERROR: the Bayes learn function returned an error.\n";
        }
        elsif ($learned == 1 && $debug == 1) {   # 1=message was learned.  0=message wasn't learned
                print "Message learned.\n";
        }
        elsif ($learned == 0 && $debug == 1) {
                print "Message not learned.\n";
        }
}

# Purge.
$imap->expunge();
$imap->close();

$imap->disconnect();
