#!/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 launchpadlib.launchpad import Launchpad

from subprocess import *

report_folder = ""

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.bug_tasks:
        if 'debian' in task.bug_target_name:
# should be smarter and check for a watch too
# this just might mean it needs forwarding
            if task.bug_watch:
                return True, task.bug_watch.url
            else:
                return True, None
    return False, None
 
# 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')

launchpad = Launchpad.login_anonymously("check-needs-packaging", "edge")
ubuntu = launchpad.projects['ubuntu']

needs_packaging = map((lambda task: task.bug.id),
                      ubuntu.searchTasks(tags=['needs-packaging'],
                                     omit_duplicates=True,
                                     omit_targeted=False,
                                     has_no_package=True))

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

for bugid in sorted(needs_packaging, reverse=True):
    bug = launchpad.bugs[bugid]
    summary = bug.title
    useful_summary = re.sub(r'^[\[\(][Nn]eeds?[- ][Pp]ackaging[\]\)] ?', '', summary)
    software = str(useful_summary.split(" ")[0])
    if len(software) == 1:
        continue
    datafile.write('Searched for %s from <a href="https://bugs.launchpad.net/bugs/%s">%s</a><br>\n' % (software, bug.id, bug.id))
    if 'np-reviewed' in bug.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 == '':
            has_watch, url = task_checker(bug)
            if has_watch:
                datafile.write('    Already has an upstream bug watch')
                if url:
                    datafile.write(' <a href="%s">%s</a>' %(url, url))
                datafile.write('.<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()
