#!/usr/bin/python3 -I
# SPDX-FileCopyrightText: 2026 The NazoOS Contributors
# SPDX-License-Identifier: GPL-3.0-or-later
"""Boot counter of the NazoOS kernel opt-in (ADR 0008).

Run by nazoos-kernel-boot.service at every boot while kernel-nazoos is
preferred (/var/lib/nazoos/kernel-prefer). Keeps kernel-nazoos as the
default boot entry (a kernel update creates a new entry) and counts
boots of a -nazoos kernel that reach "running". A degraded boot resets
the counter. After 3 clean boots nazoos-update offers stage 2.
After "Use openSUSE kernel" it keeps kernel-default the default instead.
--grub-only: only fix the boot entry (package scripts after a kernel update).
"""

import os
import subprocess
import sys
import time
from pathlib import Path

# Same block in nazoos-welcome-helper(-strict) and nazoos-update-helper: keep them alike
# Package scripts may start us with the caller's environment: -I keeps
# PYTHONPATH and user site-packages out
# Our modules from the installed location (or the git checkout)
_src = Path(__file__).resolve().parent.parent
for base in (Path("/usr/share/nazoos-common"), _src.parent / "nazoos-common"):
    if (base / "nazoos_common").is_dir():
        sys.path.insert(0, str(base))
        break
from nazoos_common import helper, kernel, kernelstate  # noqa: E402


def main():
    try:
        flavor = kernel.keep_default()
    except (OSError, helper.Fail) as e:
        print(f"could not set the boot entry: {e}", file=sys.stderr)
        # Counting boots does not depend on it
        flavor = "nazoos" if kernelstate.PREFER.exists() else None
    if "--grub-only" in sys.argv or flavor != "nazoos":
        return 0
    release = os.uname().release
    if not kernel.running_nazoos():
        # Started kernel-default on purpose (GRUB menu): neither good nor bad
        return 0
    # Waits until the boot is finished: "running" or "degraded"
    state = subprocess.run(["systemctl", "is-system-running", "--wait"],
                           capture_output=True, text=True).stdout.strip()
    boots = kernelstate.read_boots()
    count = boots.get("count", 0) + 1 if state == "running" else 0
    kernelstate.write_boots({"count": count, "kernel": release,
                             "state": state, "time": int(time.time())})
    print(f"{release}: {state}, clean boots in a row: {count}")
    return 0


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