#!/usr/bin/perl -w
#
# xf2proc - Convert xfmail rules to procmail rules if appropriate
#
# This only handles rules on incoming messages that move or forward
# them.
#

# Submitted by Jim Hague <jim.hague@acm.org> to the xfmail@slappy.org list
# but got lost somehow in the Archimedes CVS tree. -- Wim Kerkhoff <wim@merilus.com>

use strict;
use Getopt::Long;

my $name;
my $actionNo;
my $flags;
my $folder;
my $matchField;
my $matchText;

my $mailDir = "Mail";

sub processRule;
sub printFolder;
sub usage;

GetOptions('maildir=s', \$mailDir) || usage;

open(XFRULES, "<$ARGV[0]") || die "Can't open $ARGV[0]: $!\n";

while (<XFRULES>)
{
    unless (/\@(\S*)\s(\d*)\s(\d*)\s(\S*)\s(\S*)/) {
        die "Bad input format in $ARGV[0]\n";
    }

    $name = $1;
    $actionNo = $2;
    $flags = $3;
    $folder = $4;
    $matchField = $5;
    chomp($matchText = <XFRULES>);

    # Is this a rule suitable for processing by procmail?
    if ( ($actionNo == 2 || $actionNo == 3) &&
         ($flags & 0x1fe) == 0 ) {
        processRule;
    } else {
        print "Rule $name cannot be handled by procmail.\n";
    }
}

exit(0);

sub processRule {
    print "# xfmail rule $name\n";
    print ":0 ";
    print "D" if (($flags & 1) == 0);   # Case-sensitive
    if ($matchField eq "Message") {
        print "BH";
    } elsif ($matchField eq "Body") {
        print "B";
    }
    print "\n";

    # Conditions
    print "* ";
    if ($matchField eq "Recipients") {
        print "^TO";
    } elsif ($matchField eq "Header") {
        print "^.*:.*";
    } elsif ($matchField ne "Body") {
        print "^$matchField:.*";
    }
    print "$matchText\n";

    # Actions
    if ($actionNo == 2) {       # File in folder
        printFolder;
    } elsif ($actionNo == 3) {  # Forward
        print "! $folder";
    } else {
        die "Aiiieee! Unknown action $actionNo.\n";
    }
    print "\n\n";
}

sub printFolder {
    # Is this a MBOX or MH mailbox
    if ($folder =~ /^\#mbox\/(.*)/) {
        print $1;
    } else {
        print "$mailDir/$folder/.";
    }
}

sub usage {
    print STDERR "usage: $ARG[0] [-maildir <dir>] xfmrules\n";
    exit 1;
}
