#!/usr/bin/env perl
#
# © 2009, David Paleino <dapal@debian.org>
#
# You can do whatever you want with this file, provided the above
# copyright notice is preserved.

use File::Temp qw(tempfile);

my %headers = ();
my $isFirst = 1;
my $isBody  = 0;
my $temp    = "";
my %body    = ();

open(TMPL, $ARGV[0]) || die ("Could not open file!");
while (<TMPL>) {
    my $line = $_;

    if ($isBody) {
        push @body, $line;
        next;
    }

    if ($line =~ /^\n$/) {
        # This should be the blank line between the headers and the
        # Package pseudo-header
        $isBody = 1;
    }
    else {
        chomp $line;
        $line =~ s/"/\\"/g;
        $line =~ s/'/\\'/g;

        # KMail accepts headers for which it has specific options, i.e.
        # --header "Subject: foo" is the same as giving --subject "foo".
        if ($line =~ /^\t.*$/) {
            $line =~ s/^\s*(.+[^\s])\s*$/\1/;
            push @headers, " $line";
        }
        else {
            if ($isFirst) {
                $line =~ s/^\s*(.+[^\s])\s*$/\1/;
                push @headers, " --header \"$line";
                $isFirst = 0;
            }
            else {
                $line =~ s/^\s*(.+[^\s])\s*$/\1/;
                push @headers, "\" --header \"$line";
            }
        }
    }
}
close(TMPL);
push @headers, "\"";

my ($temp, $filename) = tempfile(UNLINK => 1);
open(TMP, ">$filename") || die ("Could not open file for writing!");
print TMP join("", @body);
close(TMP);

#open(FOO, ">/tmp/mydebug");
#print FOO "$ARGV[0]\n";
#print FOO "$filename\n";

my $cmd = "kmail ".join("", @headers)." --msg ".$filename;

#print FOO "$cmd";
#close(FOO);

system($cmd);
