#!/usr/bin/env python
#
# This script reads the tile of bugs tagged needs-packaging and assumes
# the first word is the name of the software / package.  It then checks
# to see, via rmadison, if it is packaged for Ubuntu, then if it is
# packaged for Debian, then if there is a Debian ITP (Intent to Package)
# bug report or a Debian bug report requesting a package.
#
# With this information one can update an Ubuntu needs-packaging bug
# report with information that the software is already packaged, that
# the bug should be a sync request (not a needs-packaging bug), or link
# to the upstream Debian bug report.
#
# Copyright 2008 Canonical, Ltd
# Author: Brian Murray <brian@ubuntu.com>
# with props to Kees Cook
# Licensed under the GNU General Public License, version 3.

import re
import time
import urllib
import libxml2
import sys

from subprocess import *
from launchpadbugs.connector import ConnectBugList
from launchpadbugs.connector import ConnectBug

report_folder = ""

np_url = "https://bugs.launchpad.net/ubuntu/+bugs?field.searchtext=&orderby=-importance&assignee_option=any&field.assignee=&field.bug_reporter=&field.bug_supervisor=&field.bug_commenter=&field.subscriber=&field.component-empty-marker=1&field.status_upstream-empty-marker=1&field.omit_dupes.used=&field.omit_dupes=on&field.has_patch.used=&field.has_cve.used=&field.tag=needs-packaging&field.tags_combinator=ANY&field.has_no_package.used=&field.has_no_package=on&search=Search"

itp_url = "http://www.debian.org/devel/wnpp/being_packaged"
itp_xml = libxml2.htmlParseDoc(urllib.urlopen(itp_url).read(),None)
itp_list = itp_xml.xpathEval('//div[contains(@id,"inner")]/ul/li/a')

npp_url = "http://www.debian.org/devel/wnpp/requested"
npp_xml = libxml2.htmlParseDoc(urllib.urlopen(npp_url).read(),None)
npp_list = npp_xml.xpathEval('//div[contains(@id,"inner")]/ul/li/a')

def wnpp_parser(software, list):
    found = []
    for item in list:
        if item.content.lower().find(software.lower()) != -1:
            found.append(item)
    return found

def task_checker(bug_detail):
    for task in bug_detail.infotable:
        if 'debian' in task.affects.longname:
# should be smarter and check for a watch too
# this just might mean it needs forwarding
            return True
 
# Check if the amount of arguments is correct
if len(sys.argv) > 1: 
    print 'Usage: %s' % sys.argv[0]
    sys.exit(1)

now = time.localtime()
today = '%s-%s-%s' % (now[0], now[1], now[2])

datafile = open('%sneeds-packaging-run-%s.html' % (report_folder, today), 'w')

Bug = ConnectBug("text")
BugList = ConnectBugList("text")

needs_packaging = BugList(np_url)

datafile.write("<html>\n<body>\n")
datafile.write("<h1>Results of checking bugs tagged needs-packaging</h1>\n")

for bug in needs_packaging.sort("-nr"):
    bug_detail = Bug(bug.bugnumber)
    summary = bug_detail.summary
    useful_summary = re.sub(r'^[\[\(][Nn]eeds?[- ][Pp]ackaging[\]\)] ?', '', summary)
    software = useful_summary.split(" ")[0]
    if len(software) == 1:
        continue
    datafile.write('Searched for %s from <a href=%s>%s</a><br>\n' % (software, bug.url, bug.bugnumber))
    if 'np-reviewed' in bug_detail.tags:
        datafile.write('    Skipped since tagged np-reviewed.<br>\n')
        datafile.write('------------------<br>\n')
        continue
    ubuntu_results = Popen(["rmadison",software.lower()],stdout=PIPE).communicate()[0]
    if ubuntu_results != '':
        datafile.write('Ubuntu search results:<br>\n')
        datafile.write('%s<br>\n' % ubuntu_results)
        datafile.write('------------------<br>\n')
        continue
    if ubuntu_results == '':
        debian_results = Popen(["rmadison","-u","debian",software.lower()],stdout=PIPE).communicate()[0]
        if debian_results != '':
            datafile.write('Debian search results:<br>\n')
            datafile.write('%s<br>\n' % debian_results)
            datafile.write('------------------<br>\n')
            continue
        elif debian_results == '':
            if task_checker(bug_detail):
                datafile.write('    Already has an upstream bug watch.<br>\n')
                datafile.write('------------------<br>\n')
                continue
            elif wnpp_parser(software, itp_list):
                datafile.write('Debian itp search results:<br>\n')
                for item in wnpp_parser(software, itp_list):
                    datafile.write('    %s<br>\n' % item)
                datafile.write('------------------<br>\n')
                continue
            elif wnpp_parser(software, npp_list):
                datafile.write('Debian np search results:<br>\n')
                for item in wnpp_parser(software, npp_list):
                    datafile.write('    %s<br>\n' % item)
                datafile.write('------------------<br>\n')
                continue
    datafile.write('    Nothing found.<br>\n')
    datafile.write('------------------<br>\n')
datafile.write("</body>\n")
datafile.write("</html>\n")
datafile.close()
