#!/usr/bin/env python3
# Copyright (C) 2026 Micha Kranz <michasHL> - License: GNU General Public License v2
"""Checkmk agent plugin: mk_trivy_cve.

Reads Trivy scan summaries from RESULTS_DIR (default: /var/lib/trivy-cve,
overridable via /etc/check_mk/trivy_cve.cfg) and emits <<<trivy_cve:sep(0)>>>
JSON lines.

If summary.json exists in RESULTS_DIR, it is emitted directly (fast path for
large fleets). Otherwise, all *.json Trivy report files in RESULTS_DIR are
summarized on the fly.
"""

from __future__ import annotations

import collections
import json
import os
import pathlib
import sys
import time
from typing import Any

DEFAULT_CFG = pathlib.Path("/etc/check_mk/trivy_cve.cfg")
DEFAULT_RESULTS_DIR = pathlib.Path("/var/lib/trivy-cve")


def _load_config(cfg_path: pathlib.Path) -> dict[str, str]:
    cfg: dict[str, str] = {}
    if not cfg_path.is_file():
        return cfg
    for raw in cfg_path.read_text(encoding="utf-8").splitlines():
        line = raw.strip()
        if not line or line.startswith("#") or "=" not in line:
            continue
        k, v = line.split("=", 1)
        cfg[k.strip()] = v.strip().strip('"').strip("'")
    return cfg


def _summarize_report(path: pathlib.Path) -> dict[str, Any]:
    try:
        data = json.loads(path.read_text(encoding="utf-8"))
    except Exception as exc:
        return {
            "type": "target",
            "target": path.stem,
            "error": str(exc),
        }

    fix: collections.Counter[tuple[str, str]] = collections.Counter()
    total = 0
    examples: dict[str, list[str]] = {"os": [], "app": []}

    for result in data.get("Results") or []:
        kind = "os" if result.get("Class") == "os-pkgs" else "app"
        for vuln in result.get("Vulnerabilities") or []:
            total += 1
            fixed = vuln.get("FixedVersion")
            sev = vuln.get("Severity")
            if fixed and sev in ("CRITICAL", "HIGH"):
                fix[(kind, sev)] += 1
                if sev == "CRITICAL" or kind == "os":
                    first_fix = str(fixed).split(",")[0]
                    examples[kind].append(
                        f"{vuln.get('VulnerabilityID', '?')} {vuln.get('PkgName', '?')} "
                        f"{vuln.get('InstalledVersion', '?')}->{first_fix}"
                    )

    os_meta = (data.get("Metadata") or {}).get("OS") or {}
    return {
        "type": "target",
        "target": path.stem,
        "mtime": int(path.stat().st_mtime),
        "os_family": str(os_meta.get("Family", "?")),
        "os_name": str(os_meta.get("Name", "")),
        "os_critical": fix[("os", "CRITICAL")],
        "os_high": fix[("os", "HIGH")],
        "app_critical": fix[("app", "CRITICAL")],
        "app_high": fix[("app", "HIGH")],
        "total": total,
        "examples": (examples["os"] + examples["app"])[:5],
    }


def main() -> int:
    cfg_path = pathlib.Path(os.environ.get("MK_CONFDIR", "/etc/check_mk")) / "trivy_cve.cfg"
    if not cfg_path.is_file():
        cfg_path = DEFAULT_CFG
    cfg = _load_config(cfg_path)
    results_dir = pathlib.Path(cfg.get("RESULTS_DIR", str(DEFAULT_RESULTS_DIR)))
    trivy_version = cfg.get("TRIVY_VERSION", "")

    if not results_dir.is_dir():
        return 0

    print("<<<trivy_cve:sep(0)>>>")
    now = int(time.time())
    summary_file = results_dir / "summary.json"

    if summary_file.is_file():
        try:
            payload = json.loads(summary_file.read_text(encoding="utf-8"))
            targets = payload.get("targets", [])
            meta = {
                "type": "meta",
                "now": now,
                "scan_timestamp": int(payload.get("scan_timestamp", summary_file.stat().st_mtime)),
                "target_count": len(targets),
                "trivy_version": payload.get("trivy_version") or trivy_version,
            }
            print(json.dumps(meta, separators=(",", ":")))
            for item in targets:
                rec = dict(item)
                rec["type"] = "target"
                print(json.dumps(rec, separators=(",", ":")))
            return 0
        except Exception as exc:
            print(json.dumps({"type": "meta", "now": now, "error": f"summary.json unreadable: {exc}"}))
            return 0

    report_files = sorted(p for p in results_dir.glob("*.json") if p.name != "summary.json")
    if not report_files:
        print(json.dumps({"type": "meta", "now": now, "scan_timestamp": 0, "target_count": 0, "trivy_version": trivy_version}))
        return 0

    newest_mtime = max(int(p.stat().st_mtime) for p in report_files)
    meta = {
        "type": "meta",
        "now": now,
        "scan_timestamp": newest_mtime,
        "target_count": len(report_files),
        "trivy_version": trivy_version,
    }
    print(json.dumps(meta, separators=(",", ":")))
    for path in report_files:
        print(json.dumps(_summarize_report(path), separators=(",", ":")))
    return 0


if __name__ == "__main__":
    sys.exit(main())
