#! /usr/bin/perl -w

use strict;
use SOAP::Lite;

my $pkg = shift;
if (! $pkg) {
	print "Usage: $0 <package>\n";
	exit(1);
}
open(MBOX, ">", "/tmp/$pkg.mbox") || die "$!\n";
my $soap = SOAP::Lite->uri('Debbugs/SOAP')->proxy('http://bugs.debian.org/cgi-bin/soap.cgi');
$soap->on_fault( sub { print "ERROR\n" ; } );
my $bugs = $soap->get_bugs(package=>"$pkg")->result();
foreach my $bug (@$bugs) {
    print "BUG: #$bug...";
    my $result = undef;
    eval { $result = $soap->get_bug_log($bug)->result(); };
    if ($@) {
        $soap = SOAP::Lite->uri('Debbugs/SOAP')->proxy('http://bugs.debian.org/cgi-bin/soap.cgi');
        $soap->on_fault( sub { print "ERROR\n" ; } );
        next;
    }
    my $id = undef;
    foreach my $ref (@$result) {
        my @header = split(/\n/, $ref->{'header'});
        shift(@header);
        # search for Message-Id header
        unless ($id) {
            $id = (grep(/^Message-Id:/i, @header))[0];
            $id = (split(/:\s/, $id))[1] if ($id);
        }
        # Insert In-Reply-To if none found
        unless (grep(/^In-Reply-To:/i, @header)) {
            push(@header, "In-Reply-To: $id") if ($id);
        }
        # Add the bug to Reply-To
        unless (grep (/^Reply-To:/i, @header)) {
            push(@header, "Reply-To: $bug\@bugs.debian.org");
        }
        # Print everything into mbox file
        print MBOX "$_\n" foreach(@header);
        print MBOX "$_\n" foreach($ref->{'body'});
        print MBOX "@$_\n" foreach ($ref->{'attachments'});
        print MBOX "\n\n";
    }
    print "fixed\n";    
}
close MBOX;	
