#!/usr/bin/perl

# mbox_to_ezmlm - convert mbox messages to ezmlm format
# LastEditDate="Tue May 18 16:16:56 2004 by jtkeith"
# Adapted for ezmlm by John Keith <jtkeith@kavi.com>
#
# Original source:
# "Simple but Perfect" mbox to Maildir converter v0.1
# by Philip Mak <pmak@aaanime.net>

# Usage: mbox_to_ezmlm archivedir < mbox

# check for valid arguments
my ($archivedir) = @ARGV;
if (!$archivedir) {
  print STDERR "Usage: mbox_to_ezmlm archivedir < mbox\n";
  exit 1;
}

# make the archivedir if necessary
unless (-w "$archivedir") {
  mkdir $archivedir
}

# check for writable archivedir
unless (-w "$archivedir") {
  print STDERR "Cannot write to $archivedir\n";
  exit 1;
}

my $num  = 0;
my $time = time;

repeat:

# read header
my $headers = '';
my $subject = '';
while (my $line = <STDIN>) {
  # detect end of headers
  last if $line eq "\n";
  # strip "From" line from header
  $headers .= $line unless $line =~ /^From ./;
  $subject = $1 if $line =~ /^Subject: (.*)$/;
}

my $dirnum = $num / 100;
my $msgnum = $num % 100;
my $dir    = sprintf ("%s/%d-imported", $archivedir, $dirnum);
my $file   = sprintf ("%s/%02d", $dir, $msgnum);

# filter out the "DON'T DELETE THIS MESSAGE -- FOLDER INTERNAL DATA" message
$file = '/dev/null' if ($num == 0 and $subject eq "DON'T DELETE THIS MESSAGE -- FOLDER INTERNAL DATA");

# make the message directory if necessary
unless (-w "$dir") {
  mkdir $dir
}

# open output file
open (FILE, ">$file") or die "Can't open file $file: $!\n";
print FILE "$headers\n";
while (my $line = <STDIN>) {
  # detect end of message
  last if $line =~ /^From ./;
  # unescape "From"
  $line =~ s/^>From (.)/From $1/;
  print FILE $line;
}
close(FILE) or warn "Close failed for $file: $!\n";

$num++;

goto repeat unless eof(STDIN);

my $elapsed = time - $time;
print "Inserted $num messages into $archivedir in $elapsed seconds\n";
