#!/usr/bin/perl -W

# © 2007-2010, Federico Heinz <fheinz@vialibre.org.ar>
# © 2009-2010, David Paleino <dapal@debian.org>
# 
# 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 3 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, see <http://www.gnu.org/licenses/>.
#

use strict;
use URI;

die "Usage: $0 [<message file>]" unless 2 > @ARGV;

my $to = undef;
my %fields = ();
my $lastHeader = undef;

while (<>) {
    chomp;
    last if /^$/; #end of headers
    ($fields{$lastHeader} .= " $1"), next if (defined($lastHeader) && /^\s+(.*)/);
    die "Malformed header: $_" unless /([^\:]+)\:\s*(.*)/;
    my ($header, $value) = ($1, $2);
    ($lastHeader = undef), next unless $header =~ /to|cc|bcc|subject/i;
    $lastHeader = lc $header;
    $fields{$lastHeader} = $value; 
}

my $body = "";
while (<>) {
    $body .= $_;
}
$fields{'body'} = $body;

$fields{'to'} = 'submit@bugs.debian.org'; # force recipient until claws fixes a bug
    
die "Missing recipient" unless defined($fields{'to'});
my $url = URI->new("mailto:".$fields{'to'});
delete($fields{'to'});
$url->query_form(\%fields);
my $msg = "$url";
$msg =~ s/\+/ /g;
exec "claws-mail", "--compose", $msg;
