#!/usr/bin/perl -w
#
# Program to import a maildir kmail environement into a thunderbird one.

use strict;
use File::Find;
use File::Copy;
use File::Basename;
use File::Path;

my $cmd="formail";
# CHANGE AS YOU WISH
my $oldroot = "/users/segolene/.Mail";
my $newroot = "/users/segolene/.thunderbird/60q6hqwp.default/Mail/Local Folders/";
# Is the newroot a file (1) or a dir (0)
my $nrisfile = 0;
my $debug = 0;
# END CHANGE

$debug++ if ((defined $ARGV[0]) && ($ARGV[0] eq "-v"));
print "DEBUG MODE, not doing anything, just printing\n" if ($debug);
if ($debug) { 
	print "CMD1: mkdir -p $newroot\n" if ((not -d "$newroot") && (not $nrisfile));
} else {
	mkpath("$newroot",0, 0755) if ((not -d "$newroot") && (not $nrisfile));
}
system("$cmd </dev/null >/dev/null 2>/dev/null") == 0 or die "cannot find formail on your \$PATH!\nAborting";

find(\&md2mb,($oldroot));

sub md2mb {

if (-f $File::Find::name) {
	return if (
		($File::Find::name =~ /\.ids$/) ||
		($File::Find::name =~ /\.sorted$/) ||
		($File::Find::name =~ /\.index$/) ||
		($File::Find::name =~ /\/cur\//) ||
		($File::Find::name =~ /\/new\//) ||
		($File::Find::name =~ /\/tmp\//));
}
if (-d $File::Find::name) {
	return if (
		($File::Find::name =~ /\/cur$/) ||
		($File::Find::name =~ /\/new$/) ||
		($File::Find::name =~ /\/tmp$/));
}
if ($debug) { 
	print "CURR: $File::Find::name\n";
}
my $destname = $File::Find::name;
$destname =~ s|^$oldroot||;
$destname =~ s|\.([[:alnum:]éèçàù\s]*)\.directory|$1.sbd|g;
if ($debug) { 
	print "DEST: $destname\n";
}
my $cdir = dirname("$newroot/$destname");
my $outputfile="$newroot/$destname";
$outputfile="$newroot" if ($destname =~ /^\s*$/);
if (-d $File::Find::name) {
	if ($debug) { 
  		print "HANDLING: $File::Find::name content\n";
	}
	my @files = (<"$File::Find::name"/cur/*>,<"$File::Find::name"/new/*>);
	if (@files) {
		if ($debug) { 
			print "CMD2: mkdir -p $cdir\n" if (not -d "$cdir");
		} else {
			mkpath("$cdir",0, 0755) if (not -d "$cdir");
		}
	}
	foreach my $file (@files) {
  		next unless -f $file; # skip non-regular files
  		next unless -s $file; # skip empty files
  		next unless -r $file; # skip unreadable files
  		$file =~ s/'/'"'"'/;  # escape ' (single quote)
		# NOTE! The output file must not contain single quotes (')!
  		my $run = "cat '$file' | $cmd >> '$outputfile'";
		if ($debug) { 
  			print "CMD3: $run\n";
		} else {
			print "Copying maildir content from $File::Find::name to $outputfile\n";
  			system($run) == 0 or warn "cannot run \"$run\".";
		}
	}
}
if (-f $File::Find::name) {
	if ($debug) { 
		print "CMD2: mkdir -p $cdir\n" if (not -d "$cdir");
  		print "CMD3: cp $File::Find::name $cdir\n";
	} else {
		mkpath("$cdir",0, 0755) if (not -d "$cdir");
		copy($File::Find::name,$cdir);
		print "Copying mailbox content from $File::Find::name to $outputfile\n";
	}
}
}
