#!/usr/bin/perl -w
#
# courier2kmail.pl - convert a courier imap maildir repository to a kmail one
# 
# Copyright 2004 Jeremy Kerr
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

use strict;

if ($#ARGV != 1) {
	print "Usage: $0 <indir> <outdir>\n";
	print "Converts mail from a courier-imap Maildir repository (indir)\n";
	print "to a kmail Maildir repository (outdir)\n";
	exit 1;
}

my ($indir, $outdir) = @ARGV;

# ./ -> inbox/
# .one/ -> one/
# .one.two/ -> .one.directory/two/
# .one.two.three -> .one.directory/.two.directory/three

sub copy($$) {
	my ($old,$new) = @_;
	system("mkdir", "-p", "$new");
	foreach my $d ('cur', 'new', 'tmp') {
		system("cp", "-r", "$old/$d/", "$new/");
	}
}

opendir DH, $indir || die "Couldn't read $indir: $!";
foreach (readdir(DH)) {
	next if m/^\.\.$/;
	next if m/(tmp|new|cur)/;
	next unless -d "$indir/$_";
	next unless -d "$indir/$_/cur";

	my @folders = split(/\./);

	# inbox is a special case ($indir -> $outdir/inbox)
	if ( $#folders == -1 ) {
		copy($indir, "$outdir/inbox");
		next;
	}

	shift @folders;
	my $d = pop @folders;

	foreach (reverse(@folders)) {
		$d = ".$_.directory/$d";
	}

	copy("$indir/$_", "$outdir/$d");
}
closedir DH;

