#!/usr/bin/perl -w
# 
# (c) 2001++ by Gerfried Fuchs <alfie@ist.org>
# BSD licensed
# $Id: Bugs.pl,v 1.2 2004/05/17 12:59:52 alfie Exp $

use strict;
$0=~s,.*/,,;

use Getopt::Std;
my %opts = ();
getopts("hmwd:Mf:r:", \%opts);

my $dir  = $opts{d} || 'Bugs';
my $root = $opts{r};
my $file = $opts{f} || 'Summary';

if ($opts{h} || !$root) {
    print <<"USAGE";
Usage:
$0 [-h] [-m] [-w] [-d dir] -r bugroot
   -h ... show help message
   -m ... mbox only
   -w ... html only
   -d ... directory for files ("Bugs" is default)
   -M ... one big mbox file
   -f ... filename prefix for HTML overview/big mbox file (.html/.mbox added)
   -r ... root for bugreport:
          src:package ............. all bugs for the given source package name
          package ................. all bugs for the given binary package name
          maint\@addre.ss ......... all bugs for the given maintainer address
          from:submit\@addre.ss ... all bugs for the given submitter address
USAGE
    exit (0);
}

unlink <$dir/*.html>;
unlink <$dir/*.mbox>;
unlink "$file.mbox" if $opts{M};

my $overview;
{
    local $/;
    ## Get the overview
    open (IN, "wget -q -O - http://bugs.debian.org/$root|")
        || die "$0: can't get the page: $!\n";
    $overview = <IN>;
    close IN;
}

## replace the website links with local links
$overview =~ s!"[^"]*bugreport\.cgi\?bug=(\d+)[^"]*"!"$dir/$1.html"!g;

unless ($opts{m}) {
    open (OUT, ">$file.html") || die "$0: can't write $file.html: $!\n";
    print OUT $overview;
    close OUT;
}

## extract the bugreport numbers
my (@bugnumbers) = $overview =~ m!"$dir/(\d+)\.html"!g;

foreach my $bug (@bugnumbers) {
    unless ($opts{m}) {
        {
            local $/;
            ## get the different bugreports
            open (IN, "wget -q -O - http://bugs.debian.org/$bug|")
                || die "$0: can't open $dir/$bug.html: $!\n";
            $overview = <IN>;
            close IN;
        }
        ## replace the mbox links with local links
        $overview =~ s!"[^"]*bugreport\.cgi\?bug=(\d+)[^"]*&(?:amp;)?mbox=yes"!"$bug.mbox"!g;
        open (OUT, ">$dir/$bug.html") || die "$0: can't write $dir/$bug.html: $!\n";
        print OUT $overview;
        close OUT;
    }

    unless ($opts{w}) {
        ## get the mbox file
        system ("wget -q -O $dir/$bug.mbox 'http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=$bug\&mbox=yes'");
    }

    if ($opts{M}) {
        if ($opts{w}) {
            system ("cat $dir/$bug.mbox >> $file.mbox");
        } else {
            system ("wget -q -O - 'http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=$bug\&mbox=yes' >> $file.mbox");
        }
    }
}
