# Read `rpm-ostree status --json` down to the fields that answer the question.
#
# The distinction that matters is packages versus requested-packages, and
# base-local-replacements versus requested-base-local-replacements. A request
# that never becomes active is recorded in the second of each pair and absent
# from the first, and it survives a reboot looking exactly like a request that
# worked. Reading the human `rpm-ostree status` output instead is how a no-op
# gets mistaken for an applied hotfix.
#
#   ./sshx 'rpm-ostree status --json' | python3 readstate.py
#
# With --requested PREFIX it prints nothing but the requested-packages of the
# booted deployment whose name starts with PREFIX, one per line, for a caller
# that means to uninstall them. The exact strings matter: a request is recorded
# under whatever was typed to install it, so a package installed by full NEVRA
# cannot be removed by its bare name — `rpm-ostree uninstall alloy-demo` on a
# machine holding `alloy-demo-0.0.2-1.fc43.x86_64` answers "not currently
# requested" and leaves it in place. Measured 2026-08-14, and it is the whole
# reason this mode exists rather than the caller writing a package name.

import json
import sys

KEYS = (
    "base-local-replacements", "requested-base-local-replacements",
    "packages", "requested-packages",
    "base-removals", "requested-base-removals",
    "origin", "version",
)

data = json.load(sys.stdin)

if len(sys.argv) > 2 and sys.argv[1] == "--requested":
    prefix = sys.argv[2]
    for deployment in data["deployments"]:
        if not deployment.get("booted"):
            continue
        for package in deployment.get("requested-packages", []):
            if package.startswith(prefix):
                print(package)
    sys.exit(0)

for index, deployment in enumerate(data["deployments"]):
    print("--- deployment %d booted=%s staged=%s" % (
        index, deployment.get("booted"), deployment.get("staged")))
    for key in KEYS:
        if deployment.get(key):
            print("    %s = %s" % (key, deployment[key]))
