#!/usr/bin/perl -s
use Date::Parse;
use Date::Format;

our ($h, $m, $u);

if ( $h or !@ARGV ) {
    print <<USAGE;
Usage:
  $0 [-m] [-u] maildir [maildir2 ...] > mbox
     -m moves (deletes original messages) rather than copies
     -u only includes messages with unique message-IDs
USAGE
    exit 0;
}

my $move = 0;
$move=1 if ($m);
my $uniq = 0;
$uniq=1 if ($u);

my %msgids = ();

foreach my $maildir (@ARGV) {
    if ($move) {
	mkdir "$maildir/processed" or exit 1;
    }

    foreach my $subdir ("cur", "new") {
	my $dir = "$maildir/$subdir";
	opendir DIR, "$dir" or die "$dir: $!\n";
	my @files = sort {$b cmp $a} grep {!/^\./} readdir DIR;
	closedir DIR;
	foreach my $f (@files) {
	    my $file = "$dir/$f";
	    next unless (-f $file);
	    unless (open MSG, "<$file") {
		warn "$file: $!\n";
		next;
	    }
	    #warn "$file\n";
	    my @hdrs = ();
	    my %hdrs = ();
	    my $line;
	    while (defined($line=<MSG>) and ($line !~ /^$/)) {
		chomp $line;
		if ($line !~ /^\s/) {
		    push @hdrs, $line;
		} else {
		    $hdrs[$#hdrs] .= "\n$line";
		}
		my ($h, $v) = ($hdrs[$#hdrs] =~ /^([\w-]+):\s*(.*?)\s*$/s);
		$h = lc $h;
		if ($h) {
		    $hdrs{$h} = $v unless (defined $hdrs{$h});
		}
	    }

	    my $msgid = $hdrs{message-id};
	    if ($uniq and
		($msgid =~ /^<.*@.*>$/) and
		(length($msgid) > 3) ) {
		if (defined $msgids{$msgid}) {
		    warn "Skipping already seen message ID $msgid\n";
		    next;
		} else {
		    $msgids{$msgid}++;
		}
	    }

	    my $time;
	    foreach my $d ($hdrs{delivery-date},
			   (split(/;/,$hdrs{received}))[-1],
			   $hdrs{date}) {
		next unless ($d);
		$time = str2time($d);
		last if ($time);
	    }
	    $time = time() unless ($time);
	    my $datestring = time2str("%a %b %d %T %Y", $time);

	    my $from = $hdrs{from};
	    $from =~ s/\(.*?\)//gs;
	    $from =~ s/.*<(.*?)>.*/$1/gs;
	    $from = "MAILER_DAEMON\@localhost" unless $from;

	    if (@hdrs) {
		print "From $from $datestring\n";
		foreach $line (@hdrs) {
		    print "$line\n";
		}
		print "\n";

		while ($line = <MSG>) {
		    print $line;
		}
		print "\n";

		if ($move) {
		    rename $file,"$maildir/processed/$f"
			or warn "$maildir/processed/$f: $!\n";
		}
	    } else {
		warn "skipping $file\n";
	    }
	    close MSG or warn "$file: $!\n";
	}
    }
}

