#!/usr/bin/env python3
# Author: Kees Cook <kees@ubuntu.com>
# Author: Steve Beattie <sbeattie@ubuntu.com>
# Copyright (C) 2011-2020 Canonical Ltd.
#
# Reports the version of the given package in the most recent USN for it
#
# Fetch the USN database first. Override location with --database
#  wget http://people.canonical.com/~ubuntu-security/usn/database.pickle
#
from __future__ import print_function

import cve_lib
import optparse
import sys
import usn_lib
from kernel_lib import lookup_glitch_version
from source_map import version_compare
from lp_lib import UCTLaunchpad

parser = optparse.OptionParser()
parser.add_option("-D", "--database", help="Specify location of USN data (default 'database.pickle')", default="database.pickle")
parser.add_option("-r", "--release", help="Specify comma-separated list of which release to limit the search to (default is all)")
parser.add_option("-d", "--debug", dest="debug", help="Report additional debugging while processing", action='store_true')
parser.add_option("-g", "--use-glitchdb", dest="use_glitches", help="use kernel version glitchdb as fallback for last USN", action='store_true', default=False)
(opt, args) = parser.parse_args()

uctlp = UCTLaunchpad(opt)

releases = None
if opt.release:
    releases = opt.release.split(',')
else:
    releases = [r for r in cve_lib.releases if cve_lib.is_active_release(r)]

usndb = usn_lib.USNdb(args, opt.database, releases, opt)
for pkg in args:
    for rel in releases:
        usns = usndb.get_usns(pkg, rel)
        # if there are no usns reported for this package, then report
        # the earliest version in this release. Usually this script is
        # used to report pending cves between the last USN and what was
        # just published.
        if not usns:
            if opt.debug:
                print('Could not find published USN, reporting earliest publication for %s/%s' % (pkg, rel), file=sys.stderr)
            if opt.use_glitches:
                if opt.debug:
                    print('Looking up glitch version for %s/%s' % (pkg, rel), file=sys.stderr)
                version = lookup_glitch_version(pkg, rel, '~')
                if version:
                    print(version)
                else:
                    print(uctlp.get_earliest_version(rel, pkg))
            else:
                print(uctlp.get_earliest_version(rel, pkg))
        elif opt.use_glitches:
            if opt.debug:
                print('Looking up glitch version for %s/%s' % (pkg, rel), file=sys.stderr)
            version = lookup_glitch_version(pkg, rel, usns[0])
            if version:
                print(version)
            else:
                print(usns[0])
        else:
            print(usns[0])
