#!/usr/local/bin/perl
#
# This filter, to be used with Majordomo (uses some supporting scripts), 
# will re-send mail messages to alternate addresses based on some
# pattern match against the incoming mail headers.
#
# It was originally designed to split corporate broadcast email into
# separate destinations based on the Subject: of the message, but it
# can also match against other headers such as From.
#

# set our path explicitly
$ENV{'PATH'} = "/bin:/usr/bin:/usr/ucb";

# Read and execute the .cf file
$cf = $ENV{"MAJORDOMO_CF"} || "/etc/majordomo.cf";
while ($ARGV[0]) {
    if ($ARGV[0] eq "-C") {
        $cf = $ARGV[1];
        shift(@ARGV); 
    }
    if ($ARGV[0] eq "-D") {
        $delay = 1;
    }
    if ($ARGV[0] eq "-t") {
        $test = 1;
    }
    shift(@ARGV); 
}

die("$cf not readable; stopped") unless -r $cf;
die("require of majordomo.cf failed") unless require $cf;

# 1.94 has this set in $CF already
$sendmail_command = "/usr/lib/sendmail" unless $sendmail_command;

chdir($homedir) || die("Can't chdir(\"$homedir\"): $!");
unshift(@INC, $homedir);
require "majordomo.pl";

&ParseMailHeader(STDIN, *hdrs);
$reply_to = &RetMailAddr(*hdrs);
$reply_to = join(", ", &ParseAddrs($reply_to));
$in_reply_to = $hdrs{"message-id"} . ", from " . $hdrs{"from"};

# compare headers to filter table patterns
#
die("Cannot open filter table $0.cf") unless open(CF, "<$0.cf");
while (<CF>) {
    next if /^#/; next if /^$/; chop;
    local($keyw,$pattern,$dest) = m/^([^:]+):\s*([^\t]*)\s*(.*)/g;
    next unless ($keyw && $pattern && $dest);

    $keyw =~ y/A-Z/a-z/;
    print "[$keyw, \"$pattern\", $dest]\n  \"$hdrs{$keyw}\"\n" if $test;
    if ($hdrs{$keyw} =~ /$pattern/i) {
        $list = $dest;
        last;
    }
}
close(CF);

while ($delay) {
	chop($hour = `date +%H`);
	last if ($hour < 8 || $hour >= 17);
	print "...sleeping\n" if $test;
	sleep(60*10);
}

if ($test) {
    print "  -->$list\n";
    exit;
}
exit(0) unless $list;

open(MAIL, "|-") || 
    &do_exec_sendmail(split(' ',
	   "/usr/lib/sendmail -t -f$reply_to"));

print MAIL <<"EOM";
To: $list
From: $reply_to
Subject: $hdrs{"subject"}
In-Reply-To: $in_reply_to
Reply-To: $reply_to

EOM

while (<STDIN>) {
    print MAIL $_;
}

close(MAIL);
exit 0;



syntax highlighted by Code2HTML, v. 0.9.1