#!/usr/bin/env python3
# Prepare no-dsa triage for low-priority packages
# Copyright (C) 2026  Sylvain Beucler <beuc@beuc.net>
#
# 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/>.

# Follow security team's no-dsa triage for low-priority packages.

# Attention notes / limitations:
# - renamed packages (pypy->pypy3, php-phpseclib->php-phpseclib3)
#   should be considered high-priority even if not explicitely listed
# - additional triage may be needed (e.g. mark games <end-of-life>
#   rather than <postponed>)
# - lts-cve-triage.py processes the JSON export from the web tracker
#   and lags a few hours behind 'data/CVE/list'
# - priority packages need to include supported packages for ALL dists
#   bin/lts-follow-low-no-dsa <(cat .../packages-to-support-{stretch,buster,bullseye,bookworm}|sort|uniq)

# TODO:
# - lts-cve-triage.py limits the display of too many vulnerabilities
#   (replaced with '...') -- we could add an option to disable this
#   or drop this behavior if not using a tty
# - allow following triage from other dists? Even in reverse order
#   e.g. ELTS->LTS?

import setup_paths
from sectracker import parsers
import bugs

import collections
import dataclasses
import subprocess
import sys
import yaml

def bug_id(bug):
    """
    Convert CVE-date-XXXX->TEMP-btsbug-checksum.
    Makes each bug entry unique and allows cross-referencing in cvelist_ext.
    """
    # TODO: move this to lib/python/
    cve_id = bug.header.name
    if cve_id.endswith('-XXXX'):
        btsbug = 0
        for annotation in bug.annotations:
            if annotation.type != 'package':
                continue
            for flag in annotation.flags:
                if isinstance(flag, parsers.PackageBugAnnotation):
                    btsbug = flag.bug
                    break  # first btsbug id
            if btsbug > 0:
                break
        cve_id = bugs.temp_bug_name(btsbug, bug.header.description[1:-1])
    return cve_id

def main():
    print("Checking for existing no-dsa triage in low-priority packages...")

    next_lts_codename = 'trixie'
    lts_codename = 'bookworm'
    
    cves = parsers.cvelist('data/CVE/list')
    
    process = subprocess.run(['bin/lts-cve-triage.py',
                              '--skip-cache-update',
                              '--filter', 'triage_likely_nodsa'],
                             capture_output=True, encoding='UTF-8')
    
    report_package_cve_ids = collections.defaultdict(list)
    report_all_cve_ids = []
    cur_package = None
    for line in process.stdout.splitlines():
        if line.startswith('* '):
            cur_package = line.split()[1]
        if line.startswith('  - '):
            cur_cve_id = line.split()[1]
            report_package_cve_ids[cur_package].append(cur_cve_id)
            report_all_cve_ids.append(cur_cve_id)
        else:
            continue
    
    priority_packages = [p.rstrip() for p in
                         open(sys.argv[1]).readlines()]
    
    for cve in cves:
        cve_id = bug_id(cve)
        if not cve_id in report_all_cve_ids:
            continue
        no_dsa_next_lts = {}
        already_triaged = []
        for a in cve.annotations:
            if (a.type == 'package'
                and a.package not in priority_packages
                and cve_id in report_package_cve_ids[a.package]):
                if a.release == lts_codename:
                    already_triaged.append(a.package)
                if (a.kind in ('no-dsa', 'postponed', 'ignored')
                    and a.release == next_lts_codename):
                    no_dsa_next_lts[a.package] = a
        for p in no_dsa_next_lts:
            if p in already_triaged:
                continue
            next_lts_triage = no_dsa_next_lts[p]
            a2 = dataclasses.replace(next_lts_triage, release='bookworm')
            if a2.kind == 'no-dsa':
                a2.kind = 'postponed'  # LTS doesn't use "no-dsa"
            cve.annotations.insert(cve.annotations.index(next_lts_triage)+1, a2)
    
    with open('data/CVE/list', 'w') as f:
        parsers.writecvelist(cves, f)

    process = subprocess.run(['git', 'diff', '--exit-code', 'data/CVE/list'])

    if process.returncode:
        print()
        print("New triage prepared for your review in 'data/CVE/list'.")
        print("Please check 'Attention notes' in the source of this script for corner cases.")
        print("'git commit -p' may be useful.")
    else:
        print("None found.")
    
    # example: PackageAnnotation(line=1457, type='package', release='trixie', package='zstd-jni-java', kind='no-dsa', version=None, description='Minor issue', flags=[])

main()
