#!/usr/bin/env python3
# Check whether the package is affected by the provided CVE IDs
# Copyright 2025  Sylvain Beucler
#
# This file is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
#
# This file is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this file.  If not, see <https://www.gnu.org/licenses/>.

import argparse
import os
from collections import defaultdict

import setup_paths
import debian_support
from sectracker import parsers


parser = argparse.ArgumentParser(
    formatter_class=argparse.RawDescriptionHelpFormatter,
    description="""Check whether the package is affected by the provided CVE IDs.
This is meant to be used by bin/gen-DSA and bin/gen-DLA.
This helps spot mistyped or not-affected CVEs.
""",
)
parser.add_argument('dists', metavar='DISTS',
                    help='Debian release(s), comma-separated, may be empty')
parser.add_argument('package', metavar='PACKAGE',
                    help='affected package')
parser.add_argument('cve_ids', nargs='*', metavar='CVE',
                    help='CVE IDs to verify for the package')
args = parser.parse_args()

dists = args.dists.split(',')
if len(args.cve_ids) == 0:
    # gen-DSA accepts generating advisory without CVE, proceed
    raise SystemExit(0)


# Loading cvefiles takes a few seconds, keep user informed
print("Checking CVE IDs...")

# Get a list of packages linked for each CVE
# If a package is <not-affected> globally or for any DISTS, drop it (i.e. warn)
cve_files = [ s['path'] for s in debian_support.getconfig()['sources']
              if s['class'] in ['CVEFile','CVEExtendFile'] ]
valid_packages=defaultdict(set)
for path in cve_files:
    cve_entries = parsers.cvelist(os.path.dirname(__file__)
                                  + '/../data' + path)  # path=='/data/xxx/list'
    for cve_entry in cve_entries:
        cve_id = cve_entry.header.name
        if cve_id not in args.cve_ids:
            continue
        linked_packages = set()
        not_affected = set()
        for ann in cve_entry.annotations:
            if (ann.type == 'package' and ann.release is None):
                linked_packages.add(ann.package)
            if (ann.type == 'package' and ann.release in dists + [None]
                    and ann.kind == 'not-affected'):
                not_affected.add(ann.package)
        valid_packages[cve_id] |= linked_packages
        valid_packages[cve_id] -= not_affected

# Warn about mismatches
valid = True
for cve_id in args.cve_ids:
    if args.package not in valid_packages.get(cve_id,set()):
        print("warning: {} does not affect {}{}".format(
            cve_id, args.package, '/'+args.dists if args.dists else ''))
        valid = False

# Ask for confirmation
if not valid:
    ret = 'n'
    try:
        ret = input("Continue? [y/N]: ")
    except EOFError:
        pass
    if ret.lower() != 'y':
        raise SystemExit(1)
