#!/usr/bin/env python3
"""Activate the already staged JD app hub unit without root shell access."""

from __future__ import annotations

import json
import os
import pathlib
import signal
import subprocess
import time
import urllib.request


SERVICE = "jd-app-hub.service"
STATUS_URL = "http://127.0.0.1:8088/api/status"


def main() -> None:
    result = subprocess.run(
        ["/usr/bin/systemctl", "show", "--property=MainPID", "--value", SERVICE],
        check=True,
        capture_output=True,
        text=True,
    )
    pid = int(result.stdout.strip())
    if pid <= 1:
        raise RuntimeError("jd app hub has no active main process")

    process_root = pathlib.Path("/proc") / str(pid)
    if process_root.stat().st_uid != os.getuid():
        raise RuntimeError("refusing to signal a process owned by another user")
    command = (process_root / "cmdline").read_bytes().replace(b"\0", b" ").decode("utf-8", "replace")
    if "/jd-app-hub/server.js" not in command:
        raise RuntimeError("refusing to signal an unexpected process")

    os.kill(pid, signal.SIGTERM)
    for _attempt in range(40):
        try:
            with urllib.request.urlopen(STATUS_URL, timeout=2) as response:
                payload = json.load(response)
            if (
                payload.get("ok") is True
                and payload.get("service") == "jd-app-hub"
                and payload.get("version") == "2.0.1"
                and payload.get("code_channel_proxy") == "loopback-only"
            ):
                return
        except Exception:
            pass
        time.sleep(1)
    raise RuntimeError("staged JD app hub did not become version 2.0.1")


if __name__ == "__main__":
    main()
