#!/usr/bin/env python3

import cve_lib
import os
import subprocess

os.chdir(os.environ['UCT'])

# Fix check-syntax warnings about packages marked as DNE
# but who are in the trusty-esm-supported.txt list.
# Also fix for those packages trusty's state from 'end-of-life'
# to 'out of standard support'
chk_syn = subprocess.Popen('./scripts/check-syntax',
                           stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

unretire_cves = list()
while True:
    line = chk_syn.stdout.readline().decode('UTF-8')
    if line == '' and chk_syn.poll() is not None:
        break
    if "'trusty/esm'" in line:
        cve_file = line.split(':')[0]
        pkg = line.split("'")[1]
        cve = cve_lib.load_cve(cve_file)
        state, notes = cve['pkgs'][pkg]['trusty/esm']
        if 'was' not in notes:
            continue
        old_state = notes.split('was ')[1]
        cve_lib.update_state(cve_file, pkg, 'trusty/esm', old_state, None)
        state, notes = cve['pkgs'][pkg]['trusty']
        if 'end-of-life' in notes:
            cve_lib.update_state(cve_file, pkg, 'trusty', state,
                                 'out of standard support')
        # git mv retired CVE to active
        if 'retired' in cve_file and state in ['needs-triage', 'needed']:
            unretire_cves.append(cve_file)

for cve_file in set(unretire_cves):
    sp = subprocess.Popen(['git', 'mv', '-v', cve_file,
                     cve_file.replace('retired', 'active')],
                     stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    out, outerr = sp.communicate()

    if out is None:
        out = ''
    if outerr is None:
        outerr = ''

    if sp.returncode != 0:
        print ("Error moving %s: %s" % (cve_file, out+outerr))


# Fix trusty CVEs (active and retired) that are marked as
# 'end-of-life' to 'out of standard support'
(cves, uems, rcves) = cve_lib.get_cve_list_and_retired()
table = cve_lib.load_all(cves, uems, rcves)

for cve in sorted(cves):
    for pkg in sorted(table[cve]['pkgs'].keys()):
        for r in table[cve]['pkgs'][pkg].keys():
            if r == 'trusty':
                if "end-of-life" in table[cve]['pkgs'][pkg]['trusty']:
                    cve_file = cve_lib.find_cve(cve)
                    cvef = cve_lib.load_cve(cve_file)
                    state, notes = cvef['pkgs'][pkg]['trusty']
                    cve_lib.update_state(cve_file, pkg, 'trusty', state,
                                         'out of standard support')
