#!/usr/bin/python3
#
# Remove no-dsa tags from data/CVE/list
#
# Copyright © 2021 Emilio Pozuelo Monfort <pochu@debian.org>

import os.path
import sys

import setup_paths  # noqa
import config
from sectracker.parsers import cvelist, writecvelist, PackageAnnotation


def keep_annotation(cve, annotation):
    if not isinstance(annotation, PackageAnnotation):
        return True

    if cve.header.name in cves and \
       annotation.release in releases and \
       annotation.package == package:
        print(f"removing annotation for {cve.header.name}/{package}/{annotation.release}")
        return False

    return True


if len(sys.argv) <= 3:
    # assume there are no CVEs, so nothing to do
    sys.exit(0)

releases = sys.argv[1].split(",")
package = sys.argv[2]
cves = sys.argv[3:]

main_list = os.path.dirname(__file__) + '/../data/CVE/list'
# check if another file was specified in config, e.g. a ExtendedFile

for release in releases:
    distconfig = config.get_config()[release]
    if 'maincvefile' in distconfig:
        main_list = os.path.dirname(__file__) + '/../' + distconfig['maincvefile']

data = cvelist(main_list)
new_data = []

for cve in data:
    annotations = list(
        annotation
        for annotation in cve.annotations
        if keep_annotation(cve, annotation)
    )
    cve.annotations=annotations
    if not cve.annotations:
        # this shouldn't happen on a normal CVE file as we're only removing
        # the dist specific tags, but it may happen in an ExtendFile, in
        # which case we don't want to keep an empty CVE entry
        continue

    new_data.append(cve)

with open(main_list, 'w') as f:
    writecvelist(new_data, f)
