#!/usr/local/bin/perl
#
# This does a specific kinda sortm... sorts in reverse order
# on a specific textfield and date secondarily.
# It does NOT use the sortm command.  
#
# It should be executed with caution - the folder should
# be quiescent, i.e. no res or stats in progress.
#

$textfield="Priority";
$HOME="$ENV{'HOME'}";
$PWD="$ENV{'PWD'}";

##
# set the folder
#
$default="trouble";
$folder=`folder -fast`; chop $folder;

##
#parse args
#
while ($#ARGV > -1)
{
	if ( $ARGV[0] =~ /^\+(\w*)/ )
	{
		$folder = $1;
		shift;
	}
	elsif ( $ARGV[0] =~ /^-t/ )
	{
		$textfield = $ARGV[1];
		shift; shift;
	}
	elsif ( $ARGV[0] =~ /^-v/ )
	{
		$verbose = "yes";
		shift;
	}
	elsif ($ARGV[0] eq "-help" )
	{
		print "packq sorts a folder in reverse order on $textfield.\n";
		print "Usage:\tpackq [+folder] [-verbose] [-textfield value]\n";
		exit;
	}
	else
	{
		die "I Don't grok $ARGV[0]\n";
	}
}
$folder = $default if ( "$folder" eq '' ) ;


##
# set the path to the mh mail dir
#
$PROFILE="$HOME/.mh_profile";
$MAILPATH="$HOME/Mail";
open(PROFILE);
while (<PROFILE>)
{
	$MAILPATH = "$HOME/$1" if ( /^Path: (\w*)/ ) && last;
}
close(PROFILE);

##
# get the list of message numbers
# build assoc array keyed by msg number
opendir(FOLDER,"$MAILPATH/$folder") || die "Gack, $MAILPATH/$folder: $!\n";
@files = grep(/^\d/, readdir(FOLDER));
closedir(FOLDER);
chdir("$MAILPATH/$folder");

##
# move messages out of the way and get the textfield value
# make textfield value the value in 
print "getting $textfield\n" if ( $verbose eq "yes");
foreach $msg (@files)
{
	rename("$msg","#$msg");
	open(MSG,"#$msg") || print "Where did #$msg go?";
	$value = "A1";
	undef $date;
	while (<MSG>)
	{
	    $value = $1 if ( /^$textfield:\s*(\w*)/ );
	    if ( /Message-Id:\s*<(\d*)\./ )
	    {
		$date = $1;
		last;
	    }
	}
	$queue{$msg} = $value . $date;
	close(MSG);
}

##
#sort in reverse by value and put the messages back
#
print "Sorting...\n" if ( $verbose eq "yes" );
@msglist = (sort by_value_descending keys(%queue));
for ($i = 1; $i <= $#msglist + 1; $i++)
{
	print "$msglist[$i-1] becomes $i\n" if ( $verbose eq "yes");
	rename("#$msglist[$i-1]","$i");
}

##
# go back to where we started
#
chdir("$PWD");

##
# subroutines
#
sub by_value_descending
{
	$queue{$b} cmp $queue{$a};
}
