#!/usr/bin/perl -w
#
#NAME
#  tspam - Trash Spam
#
#SYNOPSIS
#  tspam [dir|folder]..
#
#DESCRIPTION
#
#OPTIONS
#
#EXAMPLES
#
#FILES
#
#BUGS
#
#SEE ALSO
#
#AUTHOR
#  John Chambers <jc@trillian.mit.edu>

$| = 1;
($P = $0) =~ s".*/"";
$V = $ENV{"V_$P"} || 1;
$exitstat = 0;

@ARGV = $ENV{'HOME'} . '/Mail/inbox' unless @ARGV;

# TBD: Handle other directories

for $d (@ARGV) {
	print "Dir: $d\n" if $V>1;
	&onedir($d);
}

exit $exitstat;

# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
sub onedir {
	local ($dir) = @_;
	local($fil); 
	for $fil (glob "$dir/*") {
		print "Fil: $fil\n" if $V>1;
		&onefile($fil); 
	}
}

# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
sub onefile {
	local($f) = @_;      
	unless (open(F,$f)) {
		printf STDEERR "$0: Can't read \"$f\" ($!)\n";
		return ($exitstat = 1);
	}
	print "Fil: $f\n" if $V>2;
	while ($l = <F>) {     
		$l =~ s/[\s\r]+$//;
		return unless $l;
		if ($l =~ /^(Subject:).*(X starts denying me access)/i) {
			&trash($f,$1,$2)
		}
	}
}

# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
sub trash {
	local($f,$h,$v) = @_;
	print "Trash \"$f\" because $h contains \"$v\"\n";
	if (system "Trash $f") {
		printf STDEERR "$0: Can't trash \"$f\" ($!)\n";
		$exitstat = $!;
		return;
	}
}

