#!/usr/bin/perl
use strict;

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

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

    # Now show the message, and mark it seen.
    system "less $msgs[$msgno-1]";

    # Mark the message seen
    my @atts;
    my $attlist = "";
    if ($msgs[$msgno-1] =~ /.*:1,(.*)$/) {$attlist = $1;}
    while ($attlist) {unshift (@atts, chop $attlist);}
    unless (grep (/S/, @atts)) {push @atts, 'S';}
    @atts = sort @atts;
    $attlist=join "", @atts;

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