#!/afs/athena/contrib/perl/p

$home = $ENV{'HOME'};
$hmail = "$home/Mail";

open(RC, "$home/.pmdrc");
while(<RC>){
    split;
    push(@match, $_[0]);
    push(@what, $_[1]);
    push(@dowhat, $_[2]);
}

@messages = split(' ', `echo $home/Mail/inbox/*`);

print("Sorting ".($#messages+1)." messages\n");
for $msg (@messages){
    @mf = split('/', $msg);
    $msgn=pop(@mf);
    next if $msgn=~/\D/;
    open(MSG, $msg);
    $mess='';
    while(<MSG>){$mess.=$_;}
#    print("Message $msgn ($msg) is $mess\n");
    if($mess=~/\nTo: (.+)/){
        $to = $1;
#       print("Message $msgn is to $to\n");
    }
    else{
	$to='';
    }
    if($mess=~/\nCc: (.+)/){
        $cc = $1;
    }
    else{
	$cc='';
    }
    if($mess=~/\nFrom: (.+)/){
        $from = $1;
    }
    else{
	$from='';
    }
    if($mess=~/\nSubject: (.+)/){
	$subject = $1;
    }
    else{
	$subject='';
    }
    
    for $i (0..$#match){
	$method = $match[$i];
	if(!defined(&$method)){
	    print("Undefined check: $method\n");
	    next;
	}
	if(&$method($what[$i])){
	    if(substr($dowhat[$i], 0, 1) ne '*'){
		&refile($dowhat[$i]);
	    }
	    else{
		$command = substr($dowhat[$i], 1);
		if($command eq 'delete'){
		    unlink("$msg");
		}
		else{
		    print("Undefinded action: $command\n");
		}
	    }
	}
    }

}

sub to {
    local($check)=@_;
    ($to=~/$check/i || $cc=~/$check/i);
}

sub from {
    local($check)=@_;
    ($from=~/$check/i);
}
sub subject {
    local($check)=@_;
    ($subject=~/$check/i);
}
sub content {
    local($check)=@_;
    ($mess=~/$check/i);
}

sub refile {
    local($box)=@_;
    $msgon=$msgn;
    while(-e "$hmail/$box/$msgn"){$msgn++;}
#    print("Refiling message $msg from $from into $box\n");
    `mv $hmail/inbox/$msgon $hmail/$box/$msgn`;
    print("New mail filed in $box\n") unless $Filed{$box};
    $Filed{$box}=1;
}
