#!/usr/bin/env python3
# Copyright 2008-2020, Canonical, Ltd
# Author: Kees Cook <kees@ubuntu.com>
# License: GPLv3
#
# This will update any "TODO" items in the secure-testing Debian CVE list
# from the Ubuntu CVE tracker.

from __future__ import print_function

from cve_lib import (
    check_mirror_timestamp, get_cve_list, load_debian_cves,
    load_ignored_reasons, prepend_debian_cve, read_config,
    update_debian_todo_cves,
)
import source_map
import optparse
import os

parser = optparse.OptionParser()
parser.add_option("-p", "--packages", help="Include known packages in the updates", action='store_true')
parser.add_option("-n", "--dry-run", help="Do not actually make changes", action='store_true')
parser.add_option("-q", "--quiet", help="Report actions verbosely", dest="verbose", default=True, action='store_false')
(opt, args) = parser.parse_args()

config = read_config()
if len(args) == 1:
    debian_cve_list = args[0]
else:
    debian_cve_list = os.path.join(config['secure_testing_path'], "data/CVE/list")

if opt.verbose:
    print("Loading Debian Sources ...")
check_mirror_timestamp(config, mirror='debian_mirror')
debian_sources = source_map.load_debian(config['debian_mirror'])['testing']

# Load known Debian CVEs
debian = load_debian_cves(debian_cve_list, verbose=opt.verbose)
reasons = load_ignored_reasons('ignored/not-for-us.txt')
ignored_reasons = dict()

# Skip stuff Debian doesn't want to ignore
for cve in sorted(reasons.keys()):
    if 'TYPO3' in reasons[cve] or 'FreeBSD' in reasons[cve]:
        #print >>sys.stderr, "Skipping %s (%s)" % (cve, reasons[cve])
        continue
    ignored_reasons.setdefault(cve, reasons[cve])

# Load known, non-embargoed CVEs
(active, embargoed) = get_cve_list()
known = [cve for cve in active if cve not in embargoed]
active = None
embargoed = None

# Look for public CVEs we know about that Debian does not yet and add them.
for cve in sorted(ignored_reasons.keys()):
    if cve not in debian:
        # FIXME: load desc (it's ignored, so no desc to load...)
        desc = ''
        prepend_debian_cve(debian_cve_list, cve, desc)

if not opt.packages:
    known = []
update_debian_todo_cves(ignored_reasons, known, debian_cve_list, debian_sources, verbose=opt.verbose, update=(not opt.dry_run))
