#!/usr/bin/perl

# conv_mail.pl - take a mail-backup file created by outlook and convert it to unix mail format
#  note: don't forget dos2unix on the file before converting!
# (c) 2002 Christian Herzog <herzog@ieee.org>
# distribute freely

use strict;

open (FILE, "$ARGV[0]");
my $mailfile = join("", <FILE>);
close FILE;

my @mails = split ("Von:\t", $mailfile);

foreach my $mail (@mails) {
	$mail = "Von:\t$mail";

	my ($head, $text) = split (/\n\n/, $mail, 2);
	my @head = split ("\n", $head);
	my ($from, $sent, $to, $subj);

	foreach (@head) {
		$from = $_ if /Von:/;
		$sent = $_ if /Gesendet:/;
		$to = $_ if /An:/;
		$subj = $_ if /Betreff:/;
	}

	$subj ||= "foo";

	$from =~ s/Von:\t//;
	$from =~ s/\[(.+)\]/<\1>/;
	$sent =~ s/Gesendet:\t//;
	$to =~ s/An:\t//;
	$subj =~ s/Betreff:\t//;

	my ($name, $addr) = split (/ </, $from);
	$addr = '<' . $addr;
	$name = "\"$name\"";

	my ($date1, $date2) = conv_date($sent);

	if ($to ne '') {
		print <<EOF;
From $name  $date1
Return-Path: $addr
Date: $date2
From: $name $addr
To: $to
Subject: $subj

$text
EOF
	}
}


sub conv_date {
	$_ = @_[0];
	my ($day, $daynum, $month, $year, $hour, $min) = /(\w+), (\d+)\. (\S+) (\d+) (\d+):(\d+)/;

	$day =~ s/Montag/Mon/;
	$day =~ s/Dienstag/Tue/;
	$day =~ s/Mittwoch/Wed/;
	$day =~ s/Donnerstag/Thu/;
	$day =~ s/Freitag/Fri/;
	$day =~ s/Samstag/Sat/;
	$day =~ s/Sonntag/Sun/;

	$month =~ s/Januar/Jan/;
	$month =~ s/Februar/Feb/;
	$month =~ s/März/Mar/;
	$month =~ s/April/Apr/;
	$month =~ s/Mai/May/;
	$month =~ s/Juni/Jun/;
	$month =~ s/Juli/Jul/;
	$month =~ s/August/Aug/;
	$month =~ s/September/Sep/;
	$month =~ s/Oktober/Oct/;
	$month =~ s/November/Nov/;
	$month =~ s/Dezember/Dec/;

	my $sec = '00';

	my $date1 = "$day $month $daynum $hour:$min:$sec $year";
	my $date2 = "$day, $daynum $month $year $hour:$min:$sec +0100";
	
	return $date1, $date2;
}
