# Copyright (C) 2005-2016 Canonical Ltd.
# Author: Kees Cook <kees@ubuntu.com>
# Author: Jamie Strandboge <jamie@ubuntu.com>
#
# This script is distributed under the terms and conditions of the GNU General
# Public License, Version 2 or later. See http://www.gnu.org/copyleft/gpl.html
# for details.

import optparse, os, sys, time, urllib
from ivulncheck_api.lib.uct import  cve_lib
from ivulncheck_api.lib.uct import  support_tool
from cgi import escape

from ivulncheck_api.lib.uct import source_map


def ubuntuTable(release):
    # ~ cve_lib.init()
    
    map = source_map.load()
    releases = cve_lib.all_releases
    
    tables = []
    
    only_release = release
    no_retired = True

    support_db = None

    if len(cve_lib.devel_release) > 0:
        if only_release:
            releases = [only_release]

    for eol in cve_lib.eol_releases:
        if eol in releases:
            releases.remove(eol)

    (cves, cves_retired, uems) = cve_lib.get_cve_list()
    
    (table, priority, cves, namemap, cveinfo) = cve_lib.load_table(cves, cves_retired, uems)

    for cve in sorted(cves):
        
        cve_needed = False
        for pkg in sorted(table[cve].keys()):

            action_needed = False   # A package in any release needs updating
            released = False        # A package in any release has been fixed
            supported = False       # A package in any release is supported and needs to be fixed
            partner = False         # A package in any release is partner-supplied
            mark = dict()
            for rel in releases:
                release = rel
                pkg_rel_supported = False  # Package in *this* release is supported

                mark.setdefault(rel, "")

                # Find any unlisted items and decide if they are DNE or needs-triage
                if rel not in table[cve][pkg]:
                    table[cve][pkg].setdefault(rel, 'needs-triage')
                    if pkg not in map[release]:
                        table[cve][pkg][rel] = 'DNE'

                # Check if package is supported on this release
                pkgname = pkg
                if pkg in namemap and rel in namemap[pkg]:
                    pkgname = namemap[pkg][rel]
                if cve_lib.is_supported(map, pkgname, rel, cveinfo[cve]):
                    pkg_rel_supported = True

                # Is it already released?
                if table[cve][pkg][rel] in ['released']:
                    released = True
                    action_needed = True

                # Is is needed still?
                if table[cve][pkg][rel] in ['needed', 'deferred', 'pending', 'needs-triage', 'active']:
                    action_needed = True
                    # Does this package need attention for a supported release?
                    if pkg_rel_supported:
                        supported = True

                # A partner issue?
                if cve_lib.is_partner(map, pkg, rel):
                    partner = True

            if action_needed:
                    
                for rel in releases:
                    pkg_status = table[cve][pkg][rel]
                    if table[cve][pkg][rel] in ['active', 'deferred']:
                        pkg_status = 'needed'
                    fixed_versions = []
                    if pkg_status == 'released':
                        try:
                            if len(cveinfo[cve]['pkgs'][pkg][rel]) > 1:
                                fixed_versions = cveinfo[cve]['pkgs'][pkg][rel][1:]
                        except KeyError as ke:
                            pass
                    if pkg in priority[cve]:
                        urgency = priority[cve][pkg]
                    else:
                        urgency = priority[cve]['default']
                    tables.append({'cve_id': cve, 'src_package': pkg, 'fixed_versions': fixed_versions, 'urgency': urgency, 'pkg_status': pkg_status})
            
                cve_needed = True

    return tables

