#!/usr/local/bin/perl -dw
#
#NAME
#  Rmm - trash the current email message
#
#SYNOPSIS
#  Rmm [+folder] [messages]..
#
#REQUIRES
#
	$LNAM = $ENV{'LOGNAME'} || $ENV{'USER'};
	$HOME = $ENV{'HOME'} || "/home/$LNAM";
	@INC = ($HOME, "$HOME/mh","$HOME/sh",@INC);
	require 'jcmh.pm';
#
#DESCRIPTION
#  This lists messages from an mh-style directory.
#
#OPTIONS
#
#EXAMPLES
#
#FILES
#
#BUGS
#
#SEE ALSO
#
#AUTHOR
#  John Chambers <jc@trillian.mit.edu>

$| = 1;

for $a (@ARGV) {
	print "$P: Arg \"$a\"\n" if $V>2;
	if ($a =~ /^\+(\w+)$/) {
		$FLDR = $1;
		print "Folder \"$FLDR\" from command line.\n" if $V>2;
	} elsif ($a =~ /^\d+$/) {
		++$trashed;
	} elsif ($a =~ /^\d/) {
		&rmlist($a);
	} else {
		print STDERR "$P: Unrecognized arg \"$a\" ignored.\n";
		++$trashed;	# Suppress trashing of current message.
	}
}
exit 0 if $trashed > 0;

unless ($rmcnt) {	# Were there any files listed?
	$ndx = &getindex($MDIR,$FLDR,1);
	print "--- Delete message $ndx (current)\n" if $V>1;
	&rmfiles($ndx,$ndx);
	exit 0;
}
exit 1;

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
sub rmfiles {
	local($lo,$hi) = @_;
	local($n,$pth);
	$hi = $lo unless $hi >= $lo;
	for ($n = $lo; $n <= $hi; $n++) {
		++$rmcnt;
		print "Delete: message $n.\n" if $V>2;
		$pth = "$MDIR/$FLDR/$n";
		if (-f $pth) {
			if (unlink($pth)) {
				print "Deleted message $n.\n" if $V>1;
			} else {
				print STDERR "Can't delete $n ($!)\n";
			}
		} else {
			print STDERR "Can't delete $n (no such message)\n";
		}
	}
}

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
sub rmlist {
	local($lst) = @_;
	local($lo,$hi,$rmdr);
	while(($lo,$rmdr) = ($lst =~ /^(\d+)(.*)$/)) {
		if (($hi,$rmdr) = ($rmdr =~ /^-(\d+)(.*)$/)) {
			&rmfiles($lo,$hi);
		} elsif ($rmdr =~ s/^,//) {
			&rmfiles($lo,$lo);
		} else {
			&rmfiles($lo,$lo);
		}
		($lst = $rmdr) =~ s/^,//;
	}
	if ($lst) {
		print STDERR "$P: Can't parse message list \"$lst\"\n";
	}
}
