#!/opt/bin/perl

use strict;
use Mail::Internet;
use LWP::UserAgent;
use HTTP::Request::Common qw(POST);

# A little hack which takes emails and pops them into sourceforge's bug
# tracking system.
#
# josh@hitchhiker.org

my $bug_email = 'lily-bugs@sky.net';
my $bug_url   = 'http://sourceforge.net/bugs/index.php?group_id=16060';

my $mailin=new Mail::Internet(\*STDIN);

# play it safe.
exit 0 if ($mailin->get('X-LilyBug-Loop:'));

my @lines = @{$mailin->body()};
chomp(@lines);
my $body = join "\n",@lines;

my $subject = substr($mailin->get("Subject:"),0,55);
chomp($subject);
$subject ||= "[no summary]";

my %form_variables = (func         => "postaddbug",
                      group_id     => 16060,   # lilyCore
		      category_id  => 100,     # None
                      bug_group_id => 100,
                      summary      => $subject,
                      details      => $body, 
		      SUBMIT       => "SUBMIT");

use Data::Dumper;
print Dumper \%form_variables;

		      
my $ua = LWP::UserAgent->new;
   $ua->agent("lily-bug-report/0.1");
   
my $req = POST $bug_url, [%form_variables];

my $response = $ua->request($req)->as_string;

my $mailout = $mailin->reply();

if ($response =~ /^[345]\d+ (.*)/ || $response =~ /ERROR\s*(.*)/) {
    my $errormsg = $1;
    $errormsg =~ s/<[^>]+>//g;
    $errormsg =~ s/^\s*//g;
    $errormsg =~ s/\s*$//g;
    @{$mailout->body()} = (
      "ERROR: $errormsg.\n",
      "\n",
      "For more information, please refer to\n",
      "    $bug_url.\n"
    );
} else {
    @{$mailout->body()} = (
      "Thank you for your bug report.\n",
      "\n",
      "For more information, please refer to\n",
      "   $bug_url.\n"
    );
}

$mailout->replace("From:", $bug_email);
$ENV{MAILADDRESS}=$bug_email;

#open(F, ">/tmp/zzztest");
#$mailout->print(\*F);
#print F $response;
#close(F);

# send the reply back at em.

$mailout->add('X-LilyBug-Loop:', 'yes');
$mailout->smtpsend();
