#!/usr/bin/python

from arsenal.arsenal_lib import *
from lpltk import LaunchpadService

if len(sys.argv) < 1:
    sys.stderr.write("Usage: %s <source-package>\n" %(sys.argv[0]) )
    sys.exit(1)

total_count = 0
source_pkgs = sys.argv[1:]
lp          = LaunchpadService(config={'read_only':True})
d           = lp.launchpad.distributions["ubuntu"]

print "== Bugs open upstream =="
print

for source_pkg in source_pkgs:
    s = d.getSourcePackage(name = source_pkg)
    bug_tracker_url = None
    up = s.upstream_product
    if (up is not None and up.bug_tracker is not None):
        bug_tracker_url = up.bug_tracker.base_url

    print "%s (%s - %s):" %(source_pkg, up.name, bug_tracker_url)

    upstream_tasks = s.searchTasks(status_upstream = 'open_upstream')
    print "%d upstreamed bugs for %s" %(len(list(upstream_tasks)), source_pkg)

    count = 0
    for bugtask in upstream_tasks:
        print bugtask.bug.id, bugtask.bug_target_display_name

        for sibling_task in bugtask.related_tasks:
            watch = sibling_task.bug_watch
            if watch is None:
                print "  %s" %(sibling_task.bug_target_display_name)
                continue

            watch_tracker = watch.bug_tracker.base_url
            print "  %s [%s]" %(sibling_task.bug_target_display_name,
                                watch_tracker)

            if watch_tracker == bug_tracker_url:
                count += 1
                break

    print "%d officially upstreamed bugs for %s" %(count, source_pkg)
