#!/usr/bin/perl

use List::MoreUtils qw(uniq nsort_by);
use LaTeX::Encode qw(latex_encode);
use XMLRPC::Lite;
use Data::Dumper;

# four files: 
# - bur: input file, unsorted list of bug numbers, may contain duplicates, 
#        generated by LaTeX
# - but: cache of bug titles; format: one bug per two lines
#        * first line bug number
#        * second line bug title
#        maintained by this script, can be deleted any time but needs bugzilla
#        access for recreation
# - bux: manually generated index keyword file for bugs; format: one bug per two 
#        lines
#        * first line bug number
#        * second line bug keywords, separated by ";"
# - bug: output file, LaTeX fragment that can be sourced

# Initialization for the BZ
my $proxy = XMLRPC::Lite->proxy("https://bugs.gentoo.org/xmlrpc.cgi");


# Fetch the title of a bug from Bugzilla
sub getbugtitle {
  my $number=shift;
  my $soapresult = $proxy->call('Bug.get', { ids => [$number] });
  my $result = $soapresult->result;
  my $bug = $result->{bugs}->[0];
  my $summary = $bug->{summary};
  return $summary;
}

# Encode a bug title so it can be printed by LaTeX
sub encodebugtitle {
  return latex_encode(shift);
};


# Main code start

# Read the list of bugs referenced in the LaTeX file.
open my $bur, '<', "decisions.bur";
my @burlist = <$bur>;
close $bur;
chomp @burlist;

my @bugnumbers=uniq nsort_by { $_ } @burlist;

# Read the cache of bug titles; this file can be deleted, but recreating or
# updating it requires internet access.
open my $but, '<', "decisions.but";
my @butlist = <$but>;
close $but;
chomp @butlist;

my %bugtitles=@butlist;


# Read the bug index keywords
open my $bux, '<', "decisions.bux";
my @buxlist = <$bux>;
close $bux;
chomp @buxlist;

my %bugkeywords=@buxlist;


# Loop through the referenced bug numbers, check if we already have the title,
# and if not fetch and add it.
foreach(@bugnumbers) {
  my $cur=$_;
  print "Bug number $cur\n";
  if ($bugtitles{$cur}) {
    print "  Title is \"$bugtitles{$cur}\"\n";
  } else {
    print "  Title not yet available, fetching it\n";
    $bugtitles{$cur}=getbugtitle($cur);
    print "    Result is \"$bugtitles{$cur}\"\n";
  };
};

# Write out the bug title cache again.
my @butlistnew= map { $_ => $bugtitles{$_} } sort keys %bugtitles;
open my $but, '>', "decisions.but";
print $but "$_\n" for @butlistnew;
close $but;

# Write out the TeX input file
open my $bug, '>', "decisions.bug";
print $bug '\renewcommand{\gentoobugtitle}[1]{%'."\n";

foreach(@bugnumbers) {
  my $cur=$_;
  my $title=encodebugtitle($bugtitles{$cur});

  my @keywords=split /;/, $bugkeywords{$cur};
  foreach(@keywords) {
    $title=$title.'\index{'.$_.'}';
  }
  print $bug '\ifthenelse{\equal{#1}{'.$cur.'}}{'.$title.'}{}%'."\n";
};

print $bug '}'."\n";
close $bug;
