#!/usr/bin/ruby -w
# ruby ../../tools/bugs2packagelist/fetchbugs.rb user usertag < list > newlist 2>log
# ruby ../../tools/bugs2packagelist/fetchbugs.rb debian-qa@lists.debian.org qa-ftbfs-20071007 < failed.2007-10-07.txt > failed.2007-10-07.txt.2 2>log
require 'soap/rpc/driver'
bts = SOAP::RPC::Driver::new('http://bugs.debian.org/cgi-bin/soap.cgi', '/Debbugs/SOAP')
bts.add_method('get_status', 'bugs')
bts.add_method('get_bugs', 'params')
bts.add_method('get_bug_log', 'params')
bts.add_method('get_usertag', 'email', 'tag')
bts.add_method('newest_bugs', 'num')

bugs = bts.get_usertag(ARGV[0], ARGV[1])
pkgs = Hash::new([])
bts.get_status(bugs[ARGV[1]].sort.uniq).each_pair do |k, v|
  pkgs[v.package] = [] if pkgs[v.package] == [] # force reinit
  pkgs[v.package] << [k, v.subject]
end

STDIN.each_line do |l|
  p, rest = l.split(' ', 2)
  matches = rest.scan(/((#\d+|NNN).*)/)
  m = matches[0]
  if matches[0].nil?
    STDERR.puts "NOTHING ON LINE: #{l}"
  else
    m = m[0]
    m.gsub!(/\s+RECHECK.*/,'')
    if m =~ /^NNN/
      if pkgs[p].length == 1
        txt = "##{pkgs[p][0][0]}: #{pkgs[p][0][1]}"
        rest.gsub!(m, txt)
      elsif pkgs[p].length > 1
        STDERR.puts "SEVERAL BUGS: #{l}"
        pkgs[p].each do |b|
          STDERR.puts " - ##{b[0]}: #{b[1]}"
        end
      else
       STDERR.puts "NO BUG FOUND: #{l}"
      end
    else # it's a bug number.
      numb = m.gsub(/^#(\d+).*/,'\1').to_i
      changed = false
      pkgs[p].each do |b|
        next if b[0] != numb
        txt = "##{b[0]}: #{b[1]}"
        rest.gsub!(m, txt)
        changed = true
      end
      if !changed
        STDERR.puts "NO MATCHING BUG: #{l}"
        pkgs[p].each do |b|
          STDERR.puts " - ##{b[0]}: #{b[1]}"
        end
      end
    end
  end
  puts "#{p} #{rest}"
end
