#!/usr/bin/python3 -I
"""Flatten `canonical-livepatch status --format json` (stdin) into KEY: value lines (stdout).

Run as root by kernelwatch-livepatch.service, whose output kernelwatch-agent reads
without needing the Livepatch snap or a shell JSON parser. Only the running
kernel's entry is used. Exits 1, printing nothing, if the input isn't Livepatch
status for a running kernel (Livepatch not enabled, or an error message)."""

import json
import sys


def clean(value):
    return " ".join(str(value).split())[:64]


def main():
    try:
        data = json.load(sys.stdin)
        entry = next(e for e in data["Status"] if e.get("Running"))
    except (ValueError, KeyError, TypeError, StopIteration, AttributeError):
        return 1
    livepatch = entry.get("Livepatch") or {}
    fixes = [f for f in livepatch.get("Fixes") or [] if isinstance(f, dict) and f.get("Patched")]
    for key, value in (
        ("STATE", livepatch.get("State")),
        ("CHECK", livepatch.get("CheckState")),
        ("SUPPORTED", entry.get("Supported")),
        ("UPGRADE-REQUIRED", entry.get("UpgradeRequiredDate")),
        ("FIXES", len(fixes)),
    ):
        if value is not None:
            print(f"LIVEPATCH-{key}: {clean(value)}")
    return 0


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