#!/usr/bin/perl

# convert an evolution imap cache into a folder

# Note: This version loses any status info stored in the .ev-summary file.

$dir = $ARGV[0];
$out = $ARGV[1];

if ($dir eq "" || $out eq "") {
    print "Usage $0 inputdir outmboxfile\n";
    exit;
}

print "Processing dir $dir into mbox $out\n";

open OUT,">>$out";

foreach $file (`ls $dir | sort -n`) {
    chop $file;
    push @files, $file;
    $files{$file} = $file;
}

foreach $file (@files) {
    if ($file eq "." || $file eq "..") {
	next;
    }

    print " $file\n";

    if ($file =~ m/^\d+\.$/) {
	open IN,"<$dir/$file";
	@body = <IN>;
	close IN;

	print OUT "From -\n";
	print OUT @body;
	print OUT "\n";
    } elsif ($file =~ m/^(\d*)\.HEAD/) {
	$base = $1;
	&add_body($base);
    } else {
	print "skipping\n";
    }
}

sub add_body {
    my $base = $_[0];
    my $boundary;
    my @head, $head;
    my $n;
    my $name;
    my @pending, $pending;

    print "Adding body $base\n";

    if ($files{$base.".MIME"}) {
	open IN,"<$base.MIME";
	@head = <IN>;
	close IN;
	print OUT @head;
    }

    if ($files{$base.".HEADER"}) {
	$name = "$dir/$base.HEADER";
    } elsif ($files{$base}) {
	open IN, "<$base";
	@head = <IN>;
	close IN;
	print OUT @head;
	print OUT "\n";
	return;
    } else {
	print OUT "\nBody of message not found\n";
	return;
    }

    open IN,"<$name";
    @head = <IN>;
    close IN;
    $head = join("",@head);

    if ($head =~ m/boundary\s*=\s*\"([^\"]*)\"/is) {
	$boundary = $1;
    } elsif ($head =~ m/boundary\s*=\s*([\S]*)/si) {
	$boundary = $1;
    } else {
	$boundary = "";
    }

    print "outputting head data $name\n";

    print OUT $head;

# this is so we 'properly' insert missing parts.

    @pending = ();
    $n = 1;
    while ($n < 50) {
	$name = $base.".".$n.".MIME";

	if ($files{"$base.$n.MIME"} || $files{"$base.$n.HEADER"} || $files{"$base.$n"}) {
	    push @pending, "$base.$n";
	    foreach $pending (@pending) {
		if ($boundary ne "") {
		    print OUT "--$boundary\n";
		}
		add_body($pending);
	    }

	    @pending = ();
	}

	$n++;
    }

    if ($boundary ne "") {
	print OUT "--$boundary--\n\n";
    }
}
