#!/usr/bin/env python3
# summary: Read or refresh reports of known software vulnerabilities.
"""starchaser vulnerabilities: known vulnerabilities in this computer's installed packages.

Usage: starchaser vulnerabilities [report | scan | summary | export [--format csv|json]]

Common commands
    starchaser vulnerabilities report     JSON: the last saved report (the daily check's or your own, whichever is newer)
    starchaser vulnerabilities scan       check now against the Arch Linux security tracker, save and print the report
    starchaser vulnerabilities export     the last report as CSV (date, machine, package, severity, fixed by update);
                                          --format json prints the full report instead

Advanced
    starchaser vulnerabilities summary    JSON: counts only (internal: Mission Control's fleet cards)

"protectionNotes" lists protection that is paused right now, in plain sentences (the app firewall waiting for a
restart after an update, say); it is empty when nothing is.
Each finding says whether an update already fixes it. Apps from Community recipes (AUR), Flatpak apps and
programming-language libraries aren't in the tracker, so they aren't checked. Nothing here needs a password.
"""
import json
import sys
from pathlib import Path

PROG = "starchaser vulnerabilities"


def load():
    for lib in (Path(__file__).resolve().parent.parent / "system/usr/local/lib/starchaser", Path("/usr/local/lib/starchaser")):
        if (lib / "vulnerabilities.py").is_file():
            sys.path.insert(0, str(lib))
            break
    import vulnerabilities
    return vulnerabilities


def main(argv):
    sys.path.insert(0, str(Path(__file__).resolve().parent))
    from starchaser_cli import safe_streams, takes_nothing_after, usage_error
    safe_streams()
    cmd = argv[0] if argv else "report"
    if cmd in ("-h", "--help", "help") or any(a in ("-h", "--help") for a in argv[1:]):
        print(__doc__.strip())
        return 0
    commands = ("report", "scan", "summary", "export")
    if cmd not in commands:
        return usage_error(PROG, f"unknown command {cmd!r}", "[report | scan | summary | export [--format csv|json]]", commands)
    fmt = "csv"
    if cmd == "export":
        rest = argv[1:]
        if rest and rest[0].startswith("--format="):
            rest = ["--format", rest[0].split("=", 1)[1], *rest[1:]]
        if rest[:1] == ["--format"]:
            if len(rest) < 2 or rest[1] not in ("csv", "json"):
                return usage_error(PROG, "--format takes csv or json", "export [--format csv|json]", ("csv", "json"))
            fmt, rest = rest[1], rest[2:]
        if rest:
            return usage_error(PROG, f"export takes only --format (got {rest[0]!r})", "export [--format csv|json]")
    elif len(argv) > 1:
        return takes_nothing_after(PROG, cmd, argv)
    try:
        v = load()
    except ImportError:
        print(f"{PROG}: Starchaser's vulnerability check isn't installed. Update Starchaser, then try again.", file=sys.stderr)
        return 1
    # protection that is paused right now (the app firewall, when its checker cannot start): said with every answer,
    # read fresh each time and never saved in the report
    notes = v.protection_notes() if hasattr(v, "protection_notes") else []
    if cmd == "scan":
        report = v.scan()
        try:
            v.save(report)
        except OSError as e:
            print(f"{PROG}: the report couldn't be saved: {e.strerror or e}", file=sys.stderr)
            print(json.dumps(report))
            return 1
        print(json.dumps({**report, "protectionNotes": notes}))
        for note in notes:
            print(f"{PROG}: {note}", file=sys.stderr)
        if not report["ok"]:
            print(f"{PROG}: {report['error']}", file=sys.stderr)
            return 1
        return 0
    report = v.latest()
    if cmd == "summary":
        print(json.dumps({**v.summary(report), "protectionNotes": notes}))
    elif cmd == "export":
        sys.stdout.write(v.to_csv(report) if fmt == "csv" else json.dumps({**report, "protectionNotes": notes}, indent=2) + "\n")
    else:
        print(json.dumps({**report, "protectionNotes": notes}))
    return 0


if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))
