#!/usr/bin/perl
use strict;

main: {
    my $maildir = shift @ARGV;
    die "usage: mdrmm maildir number" unless $maildir;
    chdir $maildir or die "can't chdir to $maildir";
    my @msgnos = @ARGV;
    die "usage: mdrmm maildir number" unless @msgnos;

    # Read in file list
    opendir CUR, "./cur" or die "can't open ./cur";
    my @msgs = grep {
	$_ = "./cur/$_"; /^\.\/cur\/[^.]/ && -f "$_"
	} readdir(CUR);
    closedir CUR;
    opendir NEW, "./new" or die "can't open ./new";
    @msgs = (@msgs, grep {
	$_ = "./new/$_"; /^\.\/new\/[^.]/ && -f "$_"
	} readdir(NEW));
    closedir NEW;
    @msgs = sort @msgs;

    my $msgno;
    foreach $msgno (@msgnos) {
	# Get the current flags
	my @atts;
	my $attlist = "";
	if ($msgs[$msgno-1] =~ /.*:1,(.*)$/) {$attlist = $1;}
	while ($attlist) {unshift (@atts, chop $attlist);}
	@atts = grep (!/T/, @atts);
	@atts = sort @atts;
	$attlist=join "", @atts;

	# Now mark the message undeleted
	my $newfile =  "$msgs[$msgno-1]";
	$newfile    =~ s:/new/:/cur/:g;
	$newfile    =~ s/:.*$//;
	$newfile   .=  ":1,$attlist" if @atts;
	rename "$msgs[$msgno-1]", "$newfile";
    }
}
