#!/usr/bin/python3 -IB
"""Collect hardware diagnostics through fixed Linux and LHM interfaces."""

import argparse
import base64
import fcntl
from functools import cache
import hashlib
import json
import os
from pathlib import Path
import platform
import re
import runpy
import signal
import stat
import subprocess
import sys
import tempfile
import time
import uuid

INSTALL = Path("/usr/libexec/linux-hw-monitor")
HERE = Path(__file__).resolve().parent
PYTHON = "/usr/bin/python3"
UMC = "lhm_umc_pinnacle_probe"
SVI2 = "lhm_pinnacle_svi2_probe"
PINNACLE_BOARD = "ROG STRIX B350-F GAMING"
LIVE_UNIT = "lhm-pinnacle-power.service"
SYSTEMCTL = "/usr/bin/systemctl"
PUBLICATIONS = (
    ("core_vid", "/run/lhm-cpu-vid/frame.json"),
    ("umc_vermeer", "/run/lhm-umc/timings-v3"),
    ("umc_vermeer", "/run/lhm-umc/timings-v2"),
    ("umc_renoir", "/run/lhm-umc/renoir-timings-v3"),
    ("umc_pinnacle", "/run/lhm-umc/pinnacle-timings-v3"),
    ("pm_table", "/run/lhm-rsmu-diagnostic/frame.json"),
)
UMC_PUBLICATIONS = ("umc_pinnacle", "umc_vermeer", "umc_renoir")


def emit(probe, status, **fields):
    print(json.dumps({"probe": probe, "status": status, **fields}, separators=(",", ":")), flush=True)


def stage_result(stage, status, reason=None, **detail):
    emit("stage_result", status, stage=stage, reason=reason, **detail)


def trusted(path):
    try:
        if path.resolve(strict=True) != path:
            return False
        return all((info := part.stat()).st_uid == 0 and not info.st_mode & 0o022
                   for part in (path, *path.parents))
    except (OSError, RuntimeError):
        return False


def command(probe, args, *, json_lines=False, text_lines=False, seconds=12):
    try:
        result = subprocess.run(args, capture_output=True, timeout=seconds, check=False)
        code, out, err = result.returncode, result.stdout, result.stderr
    except subprocess.TimeoutExpired as error:
        code, out, err = "timeout", error.stdout or b"", error.stderr or b""
    except OSError as error:
        emit(probe, "start_failed", command=args, errno=error.errno, error=str(error))
        return None, []
    rows = []
    if json_lines:
        for line in out.splitlines():
            try:
                row = json.loads(line)
                if isinstance(row, dict):
                    rows.append(row)
            except (ValueError, UnicodeError):
                emit(probe, "malformed_output", line=line[:1024].decode(errors="replace"))
        for start in range(0, len(rows), 16):
            emit(probe, "samples", data=rows[start:start + 16])
    emit(probe, "completed" if code == 0 else "failed", command=args, exit_code=code,
         stdout="" if json_lines else out[:256_000].decode(errors="replace"),
         stderr=err[:8192].decode(errors="replace"))
    return code, out.decode(errors="replace").splitlines() if text_lines else rows


def published(pm_table, probes=None, *, capture=True):
    denied = False
    statuses = {}
    for probe, name in PUBLICATIONS:
        if (probe == "pm_table" and not pm_table) or (probes is not None and probe not in probes):
            continue
        if statuses.get(probe) == "read":
            continue
        path = Path(name)
        try:
            if os.geteuid() == 0:
                path.lstat()
                if not trusted(path):
                    if capture:
                        emit(probe, "untrusted_publication", path=name)
                    statuses[probe] = "untrusted_publication"
                    continue
            with os.fdopen(os.open(path, os.O_RDONLY | os.O_CLOEXEC | os.O_NOFOLLOW | os.O_NONBLOCK), "rb") as source:
                info = os.fstat(source.fileno())
                if not stat.S_ISREG(info.st_mode) or info.st_uid != 0 or info.st_mode & 0o022 or not trusted(path):
                    if capture:
                        emit(probe, "untrusted_publication", path=name)
                    statuses[probe] = "untrusted_publication"
                    continue
                data = source.read(65_537)
            if not data or len(data) > 65_536:
                if capture:
                    emit(probe, "publication_size_out_of_range", path=name, bytes=len(data))
                statuses[probe] = "publication_size_out_of_range"
            else:
                if capture:
                    emit(probe, "publication", path=name, payload_hex=data.hex(),
                         qualification="raw_publication_requires_lhm_validation")
                statuses[probe] = "read"
        except OSError as error:
            denied |= error.errno in (1, 13)
            status = {2: "publication_missing", 13: "access_denied", 1: "access_denied"}.get(error.errno, "read_error")
            if status != "publication_missing" or probe not in statuses:
                statuses[probe] = status
            if capture:
                emit(probe, status, path=name, errno=error.errno)
    return denied, statuses


def profile(capture=True):
    if not capture:
        try:
            result = subprocess.run([PYTHON, "-IB", str(HERE / "lhm-pinnacle-power"), "--check-profile"],
                                    capture_output=True, check=False, timeout=3)
            return result.returncode == 0, json.loads(result.stdout.splitlines()[0])
        except (OSError, ValueError, IndexError, subprocess.TimeoutExpired):
            return False, {"status": "profile_probe_unavailable"}
    code, rows = command("pinnacle_profile", [PYTHON, "-IB", str(HERE / "lhm-pinnacle-power"), "--check-profile"],
                      json_lines=True)
    return code == 0, rows[0] if rows else {}


def publication_stages(board, statuses, pm_table):
    if board == "G713IC":
        for stage, probe in (("umc", "umc_renoir"), ("core_vid", "core_vid")):
            status = statuses[probe]
            stage_result(stage, "completed" if status == "read" else "skipped", status)
    if pm_table and board != PINNACLE_BOARD:
        status = statuses["pm_table"]
        if board == "G713IC" and status != "read":
            stage_result("pm_table", "skipped", "NO_SAFE_ROUTE", blocked_step="read_initial_rsp")
        else:
            stage_result("pm_table", "completed" if status == "read" else "skipped", status)


def counter_sweep(transport):
    _, rows = command("aperf_" + transport, [PYTHON, "-IB", str(HERE / "lhm-pinnacle-aperfmperf"),
                     "--generic", "--transport", transport, "--samples", "4", "--interval", "0.3"], json_lines=True)
    expected = next((row["expected_logical_cpus"] for row in rows if row.get("stage") == "inventory"), 0)
    valid = max((row.get("valid_pairs", 0) for row in rows if row.get("stage") == "sweep"), default=0)
    emit("aperf_mperf", "complete_window" if expected and valid == expected else "no_complete_window",
         transport=transport, expected_logical_cpus=expected, valid_pairs=valid)
    return expected, valid


def load_module(name, loaded, *, live=False):
    if Path("/sys/module", name).is_dir():
        emit(name, "already_loaded")
        return "already_loaded"
    kernel = platform.release()
    module = HERE / "pinnacle-diagnostics" / "modules" / kernel / (name + ".ko")
    if not trusted(module):
        emit(name, "audited_module_missing_or_untrusted", kernel=platform.release())
        return "audited_module_missing_or_untrusted"
    args = ["/usr/sbin/insmod", str(module)]
    if name == "ryzen_smu":
        args.append("lhm_pm_live=1" if live else "lhm_pm_trace=1")
    if command(name, args)[0] == 0:
        loaded.append(name)
        return "loaded"
    return "module_load_failed"


def connect_pinnacle_pm_provider(loaded, sys_root=Path("/sys"), *, live=False):
    endpoint = sys_root / "kernel/ryzen_smu_drv" / ("lhm_pm_live_frame" if live else "codename")
    if endpoint.is_file():
        return "existing_provider"
    if (sys_root / "module/ryzen_smu").is_dir():
        return "provider_loaded_without_endpoint"
    pci = sys_root / "bus/pci/devices/0000:00:00.0"
    if not pci.is_dir():
        return "root_pci_device_missing"
    if (pci / "driver").is_symlink():
        return "root_pci_device_already_bound"
    status = load_module("ryzen_smu", loaded, live=True) if live else load_module("ryzen_smu", loaded)
    if status in ("loaded", "already_loaded") and not endpoint.is_file():
        return "provider_endpoint_missing_after_load"
    return status


def diagnostic_lock():
    return os.fdopen(os.open("/run/lhm-hardware-diagnostics.lock",
                             os.O_WRONLY | os.O_CREAT | os.O_NOFOLLOW | os.O_CLOEXEC, 0o600), "wb")


def live_service_active():
    try:
        return subprocess.run([SYSTEMCTL, "--system", "is-active", "--quiet", LIVE_UNIT],
                              capture_output=True, check=False, timeout=3).returncode == 0
    except (OSError, subprocess.TimeoutExpired):
        return False


def run_live_service():
    loaded = []
    child = None
    try:
        with diagnostic_lock() as lock:
            fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
            if not Path("/dev/cpu/0/msr").exists():
                command("msr_module", ["/usr/sbin/modprobe", "msr"])
            if not Path("/sys/bus/event_source/devices/amd_df/type").is_file():
                command("amd_df_pmu", ["/usr/sbin/modprobe", "amd_uncore"])
            load_module(SVI2, loaded)
            provider = connect_pinnacle_pm_provider(loaded, live=True)
            emit("pm_provider", provider)
            child = subprocess.Popen([PYTHON, "-IB", str(HERE / "lhm-pinnacle-power"),
                                      "--publish", "--svi2", "--live-pm-table"])
        return child.wait()
    finally:
        with diagnostic_lock() as lock:
            fcntl.flock(lock, fcntl.LOCK_EX)
            if child and child.poll() is None:
                child.terminate()
                try:
                    child.wait(timeout=3)
                except subprocess.TimeoutExpired:
                    child.kill()
                    child.wait()
            for name in reversed(loaded):
                command(name + "_unload", ["/usr/sbin/rmmod", name], seconds=4)


def live_service_sample(minimum_ns):
    path = Path("/run/lhm-pinnacle-power/frame.json")
    boot = Path("/proc/sys/kernel/random/boot_id").read_text().strip()
    generation = Path("/sys/power/suspend_stats/success")
    deadline = time.monotonic() + 2.5
    while time.monotonic() < deadline:
        try:
            frame = json.loads(path.read_text(encoding="ascii")) if trusted(path) else {}
            if (frame.get("publisher") == "pinnacle-power-service"
                    and frame.get("profile") == "pinnacle-ridge-b350f-6203" and frame.get("version") == 1
                    and minimum_ns <= int(frame["monotonicNs"]) <= time.monotonic_ns()
                    and frame["bootId"] == boot and frame["suspendCount"] == int(generation.read_text())):
                return [{"status": "published", "frame": frame, "svi2": frame["svi2"], "pm": frame["pm"]}]
        except (OSError, ValueError, KeyError):
            pass
        time.sleep(0.1)
    return []


def power_stages(rows, svi_probe, pm_table, protocol=None):
    published_frames = [r for r in rows if r.get("status") == "published"]
    cores = [{k: v.get("status") for k, v in f["frame"]["values"].items() if k.startswith("core/")}
             for f in published_frames]
    valid = max((sum(s == "read" for s in frame.values()) for frame in cores), default=0)
    failures = sorted({status for frame in cores for status in frame.values() if status and status != "read"})
    vid_reason = "incomplete_core_reads" if cores else "no_fresh_publication"
    if len(failures) == 1:
        vid_reason = failures[0]
    stage_result("core_vid", "completed" if valid == 8 else "failed", None if valid == 8 else vid_reason,
                 valid_cores=valid, expected_cores=8, field_errors=failures)
    svi = [f["svi2"] for f in published_frames]
    valid_svi = any(f.get("status") == "captured" and f["flags"]["transport_rc"] == 0
                    and len(f["rails"]) == 2 and all(r["transport_rc"] == 0 for r in f["rails"]) for f in svi)
    svi_reason = svi_probe
    if svi_probe in ("loaded", "already_loaded"):
        svi_reason = svi[-1]["status"] if svi else "no_fresh_publication"
        if svi_reason == "captured":
            svi_reason = "svi2_read_failed"
    stage_result("svi2", "completed" if valid_svi else "failed", None if valid_svi else svi_reason)
    if pm_table:
        pm = [f["pm"] for f in published_frames]
        result = next((f for f in pm if f.get("status") == "read"), pm[-1] if pm else {})
        read = result.get("status") == "read"
        detail = {k: v for k, v in result.items() if k not in ("status", "payload_hex")}
        if not read and protocol and protocol.get("decode"):
            decoded = protocol["decode"]["status"]
            stage_result("pm_table", "completed" if decoded == "decoded" else "failed",
                         None if decoded == "decoded" else decoded, transport_stage="desktop_pm_protocol",
                         pm_id=protocol.get("pm_id"), payload_sha256=protocol.get("payload_sha256"),
                         publication="diagnostic_only")
        else:
            stage_result("pm_table", "completed" if read else "failed",
                         None if read else result.get("status", "no_fresh_publication"), **detail)


def pm_mapping_evidence(trace):
    entries = {}
    for line in trace:
        _, marker, tail = line.partition("lhm_pm_trace ")
        if not marker:
            continue
        label, _, fields = tail.partition(" ")
        if label in ("address_query", "buffer_range", "mapping_comparison"):
            entries[label] = dict(re.findall(r"(\w+)=([\w-]+)", fields))

    comparison = entries.get("mapping_comparison", {})
    if comparison.get("status") == "skipped":
        outcome = comparison.get("reason", "comparison_skipped")
    elif comparison.get("status") != "read":
        outcome = "comparison_not_recorded"
    elif comparison.get("base") != entries.get("buffer_range", {}).get("base") or not (
        comparison.get("bytes") == "652" and comparison.get("wb_before") == "0"
        and all(re.fullmatch(r"-1|\d{1,3}", comparison.get(key, ""))
                and int(comparison[key]) <= 652 for key in ("uc", "wb_after"))
    ):
        outcome = "incomplete_mapping_trace"
    elif "-1" in (comparison["uc"], comparison["wb_after"]):
        outcome = "mapping_failed"
    elif (comparison.get("wb_pat"), comparison.get("uc_pat"), comparison.get("wb_after_pat")) != ("6", "0", "6"):
        outcome = "cache_types_not_distinct"
    elif "0" != comparison.get("wb_after"):
        outcome = "data_appeared_during_comparison"
    elif "0" != comparison.get("uc"):
        outcome = "data_visible_only_with_uncached_mapping"
    else:
        outcome = "both_mappings_zero"
    return {"outcome": outcome, "address": entries.get("address_query", {}),
            "range": entries.get("buffer_range", {}), "comparison": comparison}


@cache
def power_tools():
    path = HERE / "lhm-pinnacle-power"
    if HERE != INSTALL and not path.exists():
        path = HERE.parent.parent / "docs/diagnostics/pinnacle-ridge/core-vid-probe.py"
    return runpy.run_path(str(path))


def decode_desktop_pm_table(payload, pm_id, pm_id_reply, transfer_status):
    return power_tools()["decode_desktop_pm_table"](payload, pm_id, pm_id_reply, transfer_status)


def pm_protocol_check(provider, rows, samples,
                      endpoint=Path("/sys/kernel/ryzen_smu_drv/lhm_pm_protocol_check")):
    commands = {"baseline_opcode": "0x3d", "baseline_arg0": 3, "desktop_opcode": "0x0a", "desktop_arg0": 0,
                "pm_id_opcode": "0x0d", "pm_id_arg0": 0}
    baseline = [row["pm"] for row in rows if row.get("status") == "published" and "pm" in row]
    if provider != "loaded":
        return dict(commands, status=provider, attempted=False)
    if len(baseline) != samples:
        return dict(commands, status="incomplete_baseline_samples", attempted=False, samples=len(baseline))
    if any(row.get("status") != "zero_filled_payload" or row.get("payload_nonzero_bytes") != 0
           for row in baseline):
        return dict(commands, status="baseline_not_all_zero", attempted=False)
    try:
        response = endpoint.read_text(encoding="ascii").strip()
    except OSError as error:
        status = {2: "protocol_endpoint_missing", 13: "protocol_access_denied",
                  1: "protocol_access_denied"}.get(error.errno, "protocol_read_failed")
        return dict(commands, status=status, errno=error.errno, attempted=False if error.errno in (1, 2, 13) else None)
    except UnicodeError:
        return dict(commands, status="invalid_protocol_evidence", attempted=None)

    skipped = re.fullmatch(r"status=skipped reason=(\w+)(?: (firmware|pat)=([\w-]+))?"
                           r"(?: pm_id_reply=(0x[0-9a-f]{1,8}) pm_id_raw=(0x[0-9a-f]{1,8}))?", response)
    if skipped:
        detail = {skipped[2]: skipped[3]} if skipped[2] else {}
        if skipped[4]:
            detail.update(pm_id_reply=skipped[4], pm_id_raw=skipped[5],
                          pm_id=skipped[5] if int(skipped[4], 16) == 1 else None,
                          decode={"status": skipped[1]})
        return dict(commands, status=skipped[1], attempted=False, **detail)
    sampled = re.fullmatch(
        r"status=sampled base=(?P<base>0x[0-9a-f]{1,8}) bytes=652 reply=(?P<reply>0x[0-9a-f]{1,8}) pat=6"
        r" before=0 immediate=(?P<immediate>\d{1,3}) after_2ms=(?P<after_2ms>\d{1,3}) after_22ms=(?P<after_22ms>\d{1,3})"
        r" uc=(?P<uc>-[12]|\d{1,3}) wb_after=(?P<wb_after>-[12]|\d{1,3})"
        r" pm_id_reply=(?P<id_reply>0x[0-9a-f]{1,8}) pm_id_raw=(?P<id_raw>0x[0-9a-f]{1,8})"
        r" frame_sample=(?P<frame_sample>immediate|after_2ms|after_22ms|uc|wb_after)"
        r" payload_hex=(?P<payload_hex>[0-9a-f]{1304})", response)
    if not sampled:
        return dict(commands, status="invalid_protocol_evidence", attempted=None, response=response[:512])

    counts = {name: int(sampled[name]) for name in ("immediate", "after_2ms", "after_22ms", "uc", "wb_after")}
    payload = bytes.fromhex(sampled["payload_hex"])
    selected = next((name for name in reversed(counts) if counts[name] > 0), "after_22ms")
    if max(counts.values()) > 652 or sampled["frame_sample"] != selected or 652 - payload.count(0) != counts[selected]:
        return dict(commands, status="invalid_protocol_evidence", attempted=True, response=response[:512])
    if int(sampled["reply"], 16) != 1:
        status = "desktop_transfer_failed"
    elif counts[selected] > 0:
        status = "desktop_transfer_populated_buffer"
    elif counts["uc"] == counts["wb_after"] == 0:
        status = "desktop_transfer_buffer_zero"
    else:
        status = "desktop_transfer_cache_comparison_unverified"
    pm_id_reply, pm_id = (int(sampled[name], 16) for name in ("id_reply", "id_raw"))
    return dict(commands, status=status, attempted=True, base=sampled["base"], bytes=652, reply=sampled["reply"],
                pat=6, before=0, frame_sample=selected, payload_hex=payload.hex(),
                payload_sha256=hashlib.sha256(payload).hexdigest(), payload_nonzero_bytes=counts[selected],
                pm_id_reply=sampled["id_reply"], pm_id_raw=f"0x{pm_id:08x}",
                pm_id=f"0x{pm_id:08x}" if pm_id_reply == 1 else None,
                decode=decode_desktop_pm_table(payload, pm_id, pm_id_reply, status),
                **{name: value if value >= 0 else None for name, value in counts.items()})


def umc_words(trace, started_at=None):
    channels = {}
    rc = None
    started = False
    for line in trace:
        prefix, marker, record = line.partition("lhm_umc_pinnacle_probe: ")
        if not marker:
            continue
        if started_at is not None:
            timestamp = re.match(r"^\[\s*(\d+)\.(\d{6})\]", prefix)
            if not timestamp or int(timestamp[1]) * 1_000_000 + int(timestamp[2]) < started_at:
                continue
        if record == "begin node=0 profile_match=1":
            started = True
            rc = None
            channels.clear()
        elif started and (match := re.fullmatch(r"umc=([01]) words=(0x[0-9a-f]{8}(?: 0x[0-9a-f]{8}){9})", record)):
            channel = int(match[1])
            if channel in channels or "0xffffffff" in match[2]:
                started = False
                continue
            channels[channel] = match[2]
        elif started and (match := re.match(r"end rc=(-?\d+)", record)):
            rc = int(match[1])
            started = False
    return channels, rc


def publish_pinnacle_umc(trace, probe_status, started_at, boot_id, directory=Path("/run/lhm-umc")):
    channels, rc = umc_words(trace, started_at)
    if probe_status != "loaded" or rc != 0 or channels.keys() != {0, 1}:
        return None
    if str(uuid.UUID(boot_id)) != boot_id or uuid.UUID(boot_id).int == 0:
        raise ValueError("invalid boot ID")
    directory.mkdir(mode=0o755, exist_ok=True)
    info = directory.lstat()
    if not stat.S_ISDIR(info.st_mode) or info.st_uid != os.geteuid() or info.st_mode & 0o022:
        raise ValueError("untrusted snapshot directory")
    data = (f"LHM-UMC-SNAPSHOT 3\nboot-id {boot_id}\nprofile pinnacle-ridge-b350f-6203\n"
            f"umc0 {channels[0]}\numc1 {channels[1]}\n")
    with tempfile.NamedTemporaryFile(mode="w", encoding="ascii", dir=directory, delete=False) as tmp:
        staged = Path(tmp.name)
        try:
            tmp.write(data)
            tmp.flush()
            os.fchmod(tmp.fileno(), 0o644)
            os.replace(staged, directory / "pinnacle-timings-v3")
        finally:
            staged.unlink(missing_ok=True)
    return hashlib.sha256(("\n".join((channels[0], channels[1]))).encode("ascii")).hexdigest()


def umc_stage(trace, probe_status, started_at=None, publication=None):
    channels, rc = umc_words(trace, started_at)
    complete = probe_status == "loaded" and rc == 0 and channels.keys() == {0, 1}
    reasons = {"already_loaded": "fresh_umc_capture_missing",
               "loaded": "incomplete_umc_trace" if rc is None or rc == 0 else "umc_read_failed"}
    reason = None if complete else reasons.get(probe_status, probe_status)
    if complete and publication not in (None, "published"):
        reason = publication
    stage_result("umc", "failed" if reason else "completed", reason, channels=sorted(channels), transport_rc=rc,
                 publication=publication)


def pinnacle(pm_table, *, memory_only=False, connect_pm=False):
    started = time.strftime("%Y-%m-%d %H:%M:%S %z")
    started_at = time.monotonic_ns() // 1000
    journal = ["/usr/bin/journalctl", "-k", "-b", "--no-pager", "--since", started, "-o", "short-monotonic"]
    loaded = []
    publication = "snapshot_publication_missing"
    use_live_service = not memory_only and live_service_active()
    try:
        umc_probe = load_module(UMC, loaded)
        if not memory_only and not use_live_service:
            svi_probe = load_module(SVI2, loaded)
        if umc_probe == "loaded":
            try:
                boot = Path("/proc/sys/kernel/random/boot_id").read_text().strip()
                for _ in range(3):
                    trace = subprocess.run(journal + ["--grep=lhm_umc_pinnacle_probe:"], check=False,
                                           timeout=3, capture_output=True).stdout.decode(errors="replace").splitlines()
                    if digest := publish_pinnacle_umc(trace, umc_probe, started_at, boot):
                        publication = "published"
                        emit("pinnacle_umc_snapshot", "published", format_revision=3, snapshot_sha256=digest)
                        break
                    time.sleep(0.1)
            except (OSError, ValueError, subprocess.TimeoutExpired) as error:
                publication = "snapshot_publication_failed"
                emit("pinnacle_umc_snapshot", "failed", error=str(error))
        if use_live_service:
            started_ns = time.monotonic_ns()
            emit("pinnacle_power", "live_window_started", monotonic_ns=str(started_ns))
            rows = live_service_sample(started_ns)
            emit("pinnacle_power", "samples", data=rows, provider=LIVE_UNIT)
            if connect_pm:
                stage_result("pm_provider", "completed", provider=LIVE_UNIT)
                emit("pm_protocol_check", "diagnostic_comparison_skipped_live_service", attempted=False)
            power_stages(rows, "already_loaded", pm_table)
        elif not memory_only:
            if connect_pm:
                provider = connect_pinnacle_pm_provider(loaded)
                connected = provider in ("loaded", "existing_provider", "already_loaded")
                stage_result("pm_provider", "completed" if connected else "failed", None if connected else provider,
                             provider=provider)
            samples = 6
            args = [PYTHON, "-IB", str(HERE / "lhm-pinnacle-power"), "--publish", "--publish-evidence",
                    "--samples", str(samples), "--svi2"]
            if pm_table:
                args.append("--pm-table")
            emit("pinnacle_power", "live_window_started", monotonic_ns=str(time.monotonic_ns()))
            _, rows = command("pinnacle_power", args, json_lines=True)
            protocol = None
            if connect_pm:
                protocol = pm_protocol_check(provider, rows, samples)
                emit("pm_protocol_check", **protocol)
            power_stages(rows, svi_probe, pm_table, protocol)
    finally:
        for name in reversed(loaded):
            command(name + "_unload", ["/usr/sbin/rmmod", name])
        _, trace = command("umc_kernel_trace", journal + [
                "--grep=lhm_umc_pinnacle_probe:|lhm_pinnacle_svi2_probe:|Lockdown:|module verification"], text_lines=True)
        if pm_table:
            code, pm_trace = command("pm_provider_kernel_trace", journal + [
                "--grep=lhm_pm_trace |ryzen_smu"], text_lines=True)
            records = sum("lhm_pm_trace " in line for line in pm_trace)
            status = ("collected" if records else "kernel_trace_missing" if "ryzen_smu" in loaded
                      else "instrumentation_not_available")
            emit("pm_provider_trace", status, records=records, journal_exit_code=code,
                 buffer_mapping=pm_mapping_evidence(pm_trace))
    umc_stage(trace, umc_probe, started_at, publication)
    return publication == "published"


def board_aml(tables=Path("/sys/firmware/acpi/tables")):
    remaining = 4 * 1024 * 1024
    complete = True
    found_dsdt = False
    for folder, names in ((tables, ("DSDT", "SSDT*")), (tables / "dynamic", ("SSDT*",))):
        prefix = "dynamic" if folder.name == "dynamic" else "static"
        for pattern in names:
            for path in sorted(folder.glob(pattern)):
                if not re.fullmatch(r"DSDT|SSDT[0-9]*", path.name):
                    continue
                name = f"{prefix}/{path.name}.aml"
                try:
                    limit = min(remaining, 192 * 1024)
                    with path.open("rb") as stream:
                        data = stream.read(limit + 1)
                except OSError as error:
                    complete = False
                    emit("board_aml", "read_error", table=name, errno=error.errno)
                    continue
                if not data or len(data) > limit:
                    complete = False
                    emit("board_aml", "size_out_of_range", table=name)
                    continue
                remaining -= len(data)
                found_dsdt |= path.name == "DSDT"
                emit("board_aml", "read", table=name, sha256=hashlib.sha256(data).hexdigest(),
                     payload_base64=base64.b64encode(data).decode("ascii"))
    return complete and found_dsdt


def board_snapshot(executable, directory, phase, mode):
    name = f"{phase}-{mode}.json"
    try:
        env = dict(os.environ, QT_QPA_PLATFORM="offscreen")
        env.pop("SENSORS_SYSFS_ROOT", None)
        result = subprocess.run([executable, "--diagnostic-hwmon-snapshot", mode],
                                capture_output=True, timeout=7, env=env, check=False)
        if result.returncode or not 0 < len(result.stdout) <= 2 * 1024 * 1024:
            emit("board_lhm", "failed", phase=phase, mode=mode, exit_code=result.returncode,
                 stderr=result.stderr[:4096].decode(errors="replace"))
            return False
        report = json.loads(result.stdout)
        if not isinstance(report, dict) or report.get("experimental_sensors_enabled") != (mode == "on"):
            emit("board_lhm", "unexpected_snapshot", phase=phase, mode=mode)
            return False
        with (directory / name).open("xb") as output:
            output.write(result.stdout)
    except (OSError, ValueError, subprocess.TimeoutExpired) as error:
        emit("board_lhm", "failed", phase=phase, mode=mode, error=str(error))
        return False
    emit("board_lhm", "captured", phase=phase, mode=mode, file=f"board/{name}")
    return True


def board_has_inputs(inventory):
    return any(chip["name"].get("value") == "it8665"
               and Path(chip["driver"].get("path", "")).name in ("it87", "lhm_it8665_wmi")
               and any(entry["attribute"].startswith(("fan", "temp"))
                       and entry.get("conversion", {}).get("status") == "converted"
                       and entry.get("fault", {}).get("value", "0") == "0" for entry in chip["inputs"])
               for chip in inventory["hwmon"]["chips"])


def verify_board_projection(directory):
    def rows(name):
        report = json.loads((directory / name).read_bytes())
        devices = {device["id"]: (device.get("topology", ""), device.get("driver", "")) for device in report["devices"]
                   if device.get("chip", {}).get("value") == "it8665"}
        return sorted((*devices[row["device_id"]], row["source"], row["channel"], row["quantity"])
                      for row in report["rows"]
                      if row.get("device_id") in devices and row.get("source") == "libsensors")

    off, on, restarted = (rows(name) for name in ("idle-off.json", "idle-on.json", "restarted-on.json"))
    expected_off = [row for row in on if row[1] == "lhm_it8665_wmi"]
    ok = bool(on) and off == expected_off and on == restarted and len(on) == len(set(on))
    stage_result("board_projection", "completed" if ok else "failed",
                 None if ok else "experimental_visibility_or_identity_mismatch",
                 off_count=len(off), on=on, restarted=restarted)


def protected_board_interfaces(sys_root):
    return any((sys_root / path).is_dir() for path in ("firmware/acpi/tables", "firmware/dmi/tables"))


def board_run(root, destination):
    probe = runpy.run_path(str(HERE / "lhm-board-hwmon"))
    sys_root = Path("/sys")
    _, matches = probe["board_identity"](sys_root)
    if root:
        outcomes = []
        if executable("/usr/sbin/dmidecode"):
            outcomes.append(command("board_smbios", ["/usr/sbin/dmidecode", "--dev-mem", "/dev/null", "--type", "34,35,36"])[0])
        else:
            stage_result("board_smbios", "skipped", "dmidecode_unavailable")
        for label, path in (("board_ioports", "/proc/ioports"), ("board_iomem", "/proc/iomem")):
            outcomes.append(command(label, ["/usr/bin/cat", path])[0])
        if matches:
            command("board_kernel_log", ["/usr/bin/journalctl", "-k", "-b", "--no-pager", "-o", "short-monotonic",
                                        "--case-sensitive=no", "--grep=it87|8665|asus|ATK0110|PNP0C14|conflict|resource"])
        complete = board_aml() and all(code == 0 for code in outcomes)
        stage_result("board_protected", "completed" if complete else "failed",
                     None if complete else "protected_inventory_incomplete")
        return

    inventory = probe["capture"]("inventory")
    protected = protected_board_interfaces(sys_root)
    stage_result("board_protected", "pending" if protected else "skipped",
                 "authorization_required" if protected else "acpi_smbios_interfaces_missing")
    emit("authorization", "required" if protected else "not_needed")
    if inventory["status"] != "captured":
        stage_result("board_inventory", "skipped", inventory["status"])
        return
    emit("board_hwmon", inventory["status"], data=inventory)
    command("board_kernel", ["/usr/bin/cat", "/proc/version", "/proc/cmdline", "/proc/modules"])
    drivers = {Path(chip["driver"].get("path", "")).name for chip in inventory["hwmon"]["chips"]}
    if matches:
        drivers.update(("eeepc_wmi", "asus_wmi_sensors", "asus_ec_sensors", "asus_atk0110", "it87", "lhm_it8665_wmi"))
    for driver in sorted(drivers - {""}):
        command("board_module", ["/usr/sbin/modinfo", "-k", platform.release(), driver])
    stage_result("board_inventory", "completed")
    if destination is None:
        stage_result("board_snapshots", "skipped", "snapshot_destination_missing")
        return
    application, output = destination
    directory = Path(output) / "board"
    directory.mkdir(mode=0o700)
    live = matches and board_has_inputs(inventory)
    live_reason = "it8665_inputs_unavailable" if matches else "it8665_profile_not_matched"
    stage_result("board_live_inputs", "completed" if live else "skipped", None if live else live_reason)

    def capture(phase, modes):
        snapshots = [board_snapshot(application, directory, phase, mode) for mode in modes]
        for sample in range(3):
            if sample:
                time.sleep(1)
            data = probe["capture"](phase)
            emit("board_hwmon", data["status"], sample=sample + 1, data=data)
        if Path("/usr/bin/sensors").is_file():
            command("board_libsensors", ["/usr/bin/sensors", "-u"])
            command("board_libsensors", ["/usr/bin/sensors", "-c", "/dev/null", "-u"])
        return all(snapshots)

    captured = capture("idle", ("off", "on"))
    stress = "/usr/bin/stress-ng"
    if live and os.access(stress, os.X_OK):
        workers = str(max(1, len(os.sched_getaffinity(0))))
        try:
            with (directory / "stress-ng.log").open("xb") as log, subprocess.Popen(
                    ["/usr/bin/timeout", "--kill-after=3s", "28s", stress, "--cpu", workers,
                     "--timeout", "25s", "--metrics-brief"],
                    stdout=log, stderr=subprocess.STDOUT) as workload:
                time.sleep(4)
                active = workload.poll() is None
                if active:
                    captured &= capture("load", ("off", "on"))
                    active = workload.poll() is None
                code = workload.wait()
            complete = active and code == 0
            stage_result("board_load", "completed" if complete else "failed",
                         None if complete else "workload_not_active_or_failed", exit_code=code)
            time.sleep(10)
            captured &= capture("recovery", ("off", "on"))
        except OSError as error:
            stage_result("board_load", "failed", "workload_start_failed", error=str(error))
    else:
        stage_result("board_load", "skipped", "stress_ng_unavailable" if live else live_reason)
    captured &= board_snapshot(application, directory, "restarted", "on")
    stage_result("board_snapshots", "completed" if captured else "failed", None if captured else "lhm_snapshot_failed")
    if live and all((directory / name).is_file() for name in ("idle-off.json", "idle-on.json", "restarted-on.json")):
        verify_board_projection(directory)


def executable(path):
    return os.access(path, os.X_OK)


def module_available(name):
    return trusted(HERE / "pinnacle-diagnostics" / "modules" / platform.release() / (name + ".ko"))


def pm_provider_available(sys_root):
    provider = sys_root / "kernel/ryzen_smu_drv"
    return all((provider / endpoint).is_file() for endpoint in ("codename", "pm_table", "pm_table_size", "pm_table_version"))


def temporary_pm_provider(sys_root):
    pci = sys_root / "bus/pci/devices/0000:00:00.0"
    return (pci.is_dir() and not (pci / "driver").is_symlink()
            and not (sys_root / "module/ryzen_smu").is_dir() and module_available("ryzen_smu"))


def publication_status(statuses, probes):
    for state in ("read", "access_denied", "untrusted_publication", "publication_size_out_of_range", "read_error"):
        if any(statuses.get(name) == state for name in probes):
            return state
    return "publication_missing"


def capabilities(sys_root=Path("/sys")):
    matched, identity = profile(capture=False)
    _, statuses = published(True, (*UMC_PUBLICATIONS, "pm_table"), capture=False)
    board_protected = protected_board_interfaces(sys_root)
    board_available = board_protected or any((sys_root / name).is_dir() for name in ("class/hwmon", "class/dmi/id", "bus/acpi"))
    audited_inputs = False
    if board_available:
        probe = HERE / "lhm-board-hwmon"
        if probe.is_file():
            board = runpy.run_path(str(probe))
            if board["board_identity"](sys_root)[1]:
                audited_inputs = board_has_inputs({"hwmon": board["hwmon"](sys_root)})
    return {
        "pinnacle_profile": matched,
        "profile_reason": identity.get("status", "profile_not_matched"),
        "umc_publication": publication_status(statuses, UMC_PUBLICATIONS),
        "temporary_umc": matched and module_available(UMC),
        "pm_publication": publication_status(statuses, ("pm_table",)),
        "pm_provider": matched and pm_provider_available(sys_root),
        "temporary_pm": matched and temporary_pm_provider(sys_root),
        "board_collector": (HERE / "lhm-board-hwmon").is_file(),
        "board_available": board_available,
        "board_protected": board_protected,
        "board_load": audited_inputs,
    }


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    mode = parser.add_mutually_exclusive_group(required=True)
    mode.add_argument("--user", action="store_true")
    mode.add_argument("--privileged", action="store_true")
    check = parser.add_mutually_exclusive_group()
    check.add_argument("--pm-table", action="store_true")
    check.add_argument("--memory-timings", action="store_true")
    check.add_argument("--connect-pm-table", action="store_true")
    check.add_argument("--start-pinnacle-power", action="store_true")
    check.add_argument("--stop-pinnacle-power", action="store_true")
    check.add_argument("--serve-pinnacle-power", action="store_true")
    check.add_argument("--boot-pinnacle-umc", action="store_true")
    check.add_argument("--board-sensors", action="store_true")
    check.add_argument("--capabilities", action="store_true")
    parser.add_argument("--board-output", nargs=2, metavar=("MONITOR", "DIRECTORY"))
    parser.add_argument("--retry-perf", action="store_true")
    parser.add_argument("--retry-publications", action="store_true")
    args = parser.parse_args()
    root = os.geteuid() == 0
    if args.privileged != root or ((args.retry_perf or args.retry_publications) and not root):
        parser.error("use an ordinary desktop process or the installed Polkit action")
    if args.board_output and (root or not args.board_sensors):
        parser.error("board snapshot output is only available in the unprivileged board run")
    if args.capabilities:
        if root:
            parser.error("hardware capability detection is an ordinary-user check")
        print(json.dumps(capabilities(), separators=(",", ":")))
        return
    if root:
        names = ("lhm-board-hwmon",) if args.board_sensors else ("lhm-pinnacle-power", "lhm-pinnacle-aperfmperf")
        collaborators = [HERE / n for n in ("lhm-hardware-diagnostics", *names)]
        if HERE != INSTALL or not all(trusted(path) for path in collaborators):
            parser.error("the privileged helper and its probes must be installed and owned by root")
        signal.signal(signal.SIGTERM, lambda *_: sys.exit(143))
    if args.board_sensors:
        if args.retry_perf or args.retry_publications:
            parser.error("board diagnostics do not use CPU probe retries")
        return board_run(root, args.board_output)
    if args.start_pinnacle_power or args.stop_pinnacle_power or args.serve_pinnacle_power:
        if not root or args.retry_perf or args.retry_publications:
            parser.error("live service management requires explicit authorization")
        if not args.stop_pinnacle_power and not profile()[0]:
            return 2
        if args.serve_pinnacle_power:
            return run_live_service()
        operation = "enable" if args.start_pinnacle_power else "disable"
        code, _ = command("pinnacle_power_service", [SYSTEMCTL, "--system", operation, "--now", LIVE_UNIT], seconds=20)
        return 0 if code == 0 else 3
    pm_table = args.pm_table or args.connect_pm_table
    emit("collector", "started", kernel=platform.release(), privileged=root, pm_table_requested=pm_table,
         memory_only=args.memory_timings, connect_pm_table=args.connect_pm_table)
    pinnacle_matched, identity = profile()
    if args.boot_pinnacle_umc:
        if not root or args.retry_perf or args.retry_publications:
            parser.error("the boot UMC snapshot requires the installed system service")
        if not pinnacle_matched:
            return 2
        with diagnostic_lock() as lock:
            fcntl.flock(lock, fcntl.LOCK_EX)
            return 0 if pinnacle(False, memory_only=True) else 3
    dmi = identity.get("dmi") or []
    board = dmi[1] if len(dmi) == 3 else None
    if args.memory_timings or args.connect_pm_table:
        stage = "umc" if args.memory_timings else "pm_table"
        sys_root = Path("/sys")
        probes = UMC_PUBLICATIONS if args.memory_timings else ("pm_table",)
        modules = all(executable(path) for path in ("/usr/sbin/insmod", "/usr/sbin/rmmod", "/usr/bin/journalctl"))
        if args.memory_timings:
            temporary = pinnacle_matched and modules and module_available(UMC)
        else:
            temporary = pinnacle_matched and (pm_provider_available(sys_root)
                                               or (modules and temporary_pm_provider(sys_root)))
        if args.user or not temporary:
            denied, statuses = published(pm_table, probes)
            status = publication_status(statuses, probes)
            if temporary or (args.user and denied):
                stage_result(stage, "pending", "authorization_required")
            else:
                stage_result(stage, "completed" if status == "read" else "skipped", status)
            if args.connect_pm_table and not temporary:
                reason = "temporary_provider_unavailable" if pinnacle_matched else "temporary_provider_profile_not_matched"
                stage_result("pm_provider", "skipped", reason)
            if args.user:
                required = temporary or denied
                emit("authorization", "required" if required else "not_needed", pinnacle=pinnacle_matched,
                     publication_retry=denied)
            return
    if args.user:
        denied, statuses = published(pm_table)
        publication_stages(board, statuses, pm_table)
        expected, valid = counter_sweep("perf")
        perf_pmu = Path("/sys/bus/event_source/devices/msr/events/aperf")
        counters = bool(expected and valid < expected and (perf_pmu.exists() or
                        any(Path("/dev/cpu").glob("[0-9]*/msr"))))
        if board == PINNACLE_BOARD:
            for stage in ("umc", "core_vid", "svi2") + (("pm_table",) if pm_table else ()):
                stage_result(stage, "pending" if pinnacle_matched else "skipped",
                             "authorization_required" if pinnacle_matched else identity.get("status", "profile_not_matched"),
                             kernel_signature=identity.get("kernel_signature"))
        elif not pinnacle_matched:
            emit("umc_pinnacle_svi2_zenplus", "no_audited_platform_route")
        emit("authorization", "required" if pinnacle_matched or counters or denied else "not_needed",
             pinnacle=pinnacle_matched, aperf_retry=counters, publication_retry=denied)
        return
    # Serialize temporary probe ownership between diagnostic sessions.
    with diagnostic_lock() as lock:
        try:
            fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
        except BlockingIOError:
            emit("collector", "privileged_session_busy")
            return
        # The profile was rechecked independently after authentication.
        if pinnacle_matched and not args.memory_timings and not any(Path("/dev/cpu").glob("[0-9]*/msr")):
            command("msr_module", ["/usr/sbin/modprobe", "msr"])
        if args.retry_publications:
            _, statuses = published(pm_table)
            publication_stages(board, statuses, pm_table)
        if args.retry_perf:
            expected, valid = counter_sweep("perf")
            if expected and valid < expected:
                if any(Path("/dev/cpu").glob("[0-9]*/msr")):
                    counter_sweep("msr")
                else:
                    emit("aperf_mperf", "msr_interface_missing")
        if pinnacle_matched:
            pinnacle(pm_table, memory_only=args.memory_timings, connect_pm=args.connect_pm_table)
        elif pm_table:
            emit("zenplus_pm_table", "profile_not_matched")


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