#!/usr/bin/env python2
# Copyright 2013, Kees Cook <kees@ubuntu.com>
# License: GPLv3
#
# Attempt to generate a report about things in pMRE status.
#
import sys, datetime
import simplejson as json

try:
    from urllib.parse import quote
    from urllib.request import urlopen
except ImportError:
    from urllib import quote, urlopen

try:
    import lpl_common
except ImportError:
    print >>sys.stderr, "lpl_common.py seems to be missing. Please create a symlink from $UQT/common/lpl_common.py to $UCT/scripts/"
    sys.exit(1)

import warnings
warnings.filterwarnings('ignore', 'apt API not stable yet', FutureWarning)
import apt

BASE_ERRORS_URL = 'https://errors.ubuntu.com/api/1.0/'


year, mon, day = [int(x) for x in sys.argv[1].split('-')]
after = datetime.datetime(year, mon, day)

lp = lpl_common.connect()
ubuntu = lp.distributions['ubuntu']
archive, group, ppa = lpl_common.get_archive("ubuntu", lp)

for pkg in sys.argv[2:]:

    for relname in ['precise','quantal','raring']:
        found = {}
        security = set()
        release = None

        rel = ubuntu.getSeries(name_or_version=relname)
        spph = archive.getPublishedSources(distro_series=rel, source_name=pkg, exact_match=True)

        for ph in spph:
            # First, record any release or security versions.
            if ph.pocket == "Security":
                security.add(ph.source_package_version)
            if ph.pocket == "Release" and ph.status == "Published":
                release = ph

        for ph in spph:
            # Not in Updates? Then we don't care.
            if ph.pocket != "Updates":
                continue
            # Same version was in Security? Then we don't care.
            if ph.source_package_version in security:
                #print >>sys.stderr, "Ignoring %s" % (ph.source_package_version)
                continue
            date = ph.date_published.replace(tzinfo=None)
            if date < after:
                continue
            datestr = date.strftime("%Y-%m-%d")
            index = datestr + "." + ph.source_package_version
            found[index] = ph

        print "    %s, %s updates: %d" % (pkg, relname, len(found))
        prior = release
        for index in sorted(found):
            ph = found[index]
            new_version = ph.source_package_version
            previous_version = prior.source_package_version
            prior = ph

            print "        %s %s" % (ph.date_published.strftime("%Y-%m-%d"),
                                     new_version)
            #print "            prior: %s" % (previous_version)
            url = '%spackage-version-new-buckets/?format=json&' % \
                    (BASE_ERRORS_URL) + \
                    'package=%s&previous_version=%s&new_version=%s' % \
                    (quote(pkg), quote(previous_version), quote(new_version))
            report = urlopen(url)
            if report.getcode() != 200:
                raise IndexError, url
            data = json.load(report)
            if 'error_message' in data.keys():
                raise IndexError, url
            count = len(data['objects'])
            #print url
            print "            error report count: %d" % (count)
