#!/usr/bin/env python2
# Copyright 2012, 2020 Canonical, Ltd.
# Author: Jamie Strandboge <jamie@canonical.com>
# License: GPLv3
#
# $UCT/scripts/report-bugs --reduced >> bugs/open.csv
#
from __future__ import print_function

import cve_lib
import optparse
import os
import sys
from lp_lib import UCTLaunchpad

parser = optparse.OptionParser()
parser.add_option("--debug", help="Verbose processing output", action='store_true')
parser.add_option("--show-bug-data", help="Show bug data", action='store_true')
parser.add_option("--lpid", help="Find bugs for Launchpad id", metavar="LPID", action='store')
parser.add_option("--subscribed-lpid", help="Show only bugs for subscribed Launchpad id", metavar="LPID", action='store')

(opt, args) = parser.parse_args()

if not opt.lpid:
    os.write(sys.stderr.fileno(), "Error: must specify --lpid\n")
    sys.exit(1)

def debug(s):
    '''Print debug message'''
    if opt.debug:
        print( "DEBUG: %s" % s, file=sys.stderr)

# Load configuration
cve_lib.read_config()

# API interface
debug("Connecting to LP ...")
lp = UCTLaunchpad(opt)

ubuntu = lp.ubuntu
debug("Distribution: %s" % ubuntu)
lpid = lp.people[opt.lpid]
debug("Launchpad id: %s" % lpid)
subscribed_lpid = None
if opt.subscribed_lpid:
    subscribed_lpid = lp.people[opt.subscribed_lpid]
    debug("Subscribed Launchpad id: %s" % subscribed_lpid)
debug("done")

debug("Loading bugs...")
bugs = {}
for rel in cve_lib.releases + ['ubuntu']:
    if rel == 'ubuntu':
        obj = ubuntu
    else:
        series = ubuntu.getSeries(name_or_version=rel)
        if not series.active:
            continue
        obj = series

    if subscribed_lpid:
        task_collection = obj.searchTasks(assignee=lpid, bug_subscriber=subscribed_lpid, omit_targeted=False, omit_duplicates=True)
    else:
        task_collection = obj.searchTasks(assignee=lpid, omit_targeted=False, omit_duplicates=True)

    for task in task_collection:
        bugid = task.bug.id
        pkg = task.bug_target_name.split(' (',1)[0]
        k = "%d:%s:%s" % (bugid, pkg, rel)
        if k not in bugs:
            debug("Adding %s" % k)
            bugs[k] = task

debug("done")

debug("Processing bugs...")
# Now go through all the bugs
keys = sorted(list(bugs.keys()))

for k in keys:
    task = bugs[k]
    bugid = k.split(":")[0]
    pkg = k.split(":")[1]
    rel = k.split(":")[2]

    extra = ""
    if opt.show_bug_data:
        extra = " (%s/%s) - %s" % (task.importance, task.status, task.bug.title)

    release = ""
    if rel != 'ubuntu':
        release = "/%s" % rel
    print(" https://launchpad.net/bugs/%s - %s%s%s" % (bugid, pkg, release, extra))

debug("done\n")
sys.exit(0)

