#!/usr/bin/perl
#SYNOPSIS
#   dm PAT
#
#DESCRIPTION
#  This searches the mail directory ~/Mail/inbox for files that contain  text
#  that matches the pattern PAT, and moves it to ~/Mail/junk. This is a quick
#  way to get rid of all messages that contain a given string
#
#  Note that this script insists on exactly one arg.  This is to prevent  the
#  disasters that can follow forgetting to quote the pattern.
#
#REQUIRES
    $HOME = $ENV{HOME} || '.';
	push @INC, "$HOME/sh";
	require "Backup.pm";
#
#AUTHOR
#  John Chambers <jc@trillian.mit.edu>

$| = 1;
$exitstat = 0;
($P = $0) =~ s".*/"";
$V = $ENV{"V_$P"} || $ENV{"D_$P"} || 2;	# Verbose level.
$how = ',';

$H = $ENV{HOME} || '.';
$M = "$H/Mail";
$I = "$M/inbox";
$J = "$M/junk";
$T = "$M/trash";

die "Usage: $0 <pattern>\n" if int(@ARGV) ne 1;		# Probably forgot a quote ;-)

for $p (@ARGV) {
	$cmd = "grep -l '$p' $I/*";
	@files = `$cmd`;
	for $f (@files) {
		$f =~ s/[\r\s]$//;
		next if $f =~ m"/,";	# Ignore "deleted" messages
		next if $f =~ m"R$";	# Ignore reply messages
		if (($dir,$msg) = ($f =~ m'^(.*)/(.*)$')) {
			print "---\t$f\n" if $V>2;
			if ($how eq ',') {
				print "rmm\t$f ...\n" if $V>1;
				($t = $f) =~ s"/(\d+)$"/,$1";
				if ($t eq $f) {
					print "### f=t='$t'\n" if $V>1;
				} else {
					print "$f => $t\n" if $V>2;
					&Backup($t) if -f $t;
					if (link($f,$t)) {
						unlink($f);
					}
				}
			} elsif ($how eq 'trash') {
				print "Trash\t$f ...\n" if $V>1;
				system "refile +trash $msg";
			} elsif ($how eq 'junk') {
				print "Junk\t$f ...\n" if $V>1;
				system "refile +junk $msg";
			} else {
				print "Delete\t$f ...\n" if $V>1;
				unlink $f;
			}
		} else {
			print "\t$f ignored.\n" if $V>1;
		}
	}
}
