#!/usr/bin/env python3
"""Root-owned Polkit helper for one strictly read-only game measurement."""

from __future__ import annotations

import argparse
import ctypes
from datetime import UTC, datetime
import json
import logging
import os
from pathlib import Path
import pwd
import re
import shutil
import stat
import subprocess
import sys
from typing import Any


COMPSIZE = shutil.which("compsize") or ""
BTRFS = shutil.which("btrfs") or ""
BTRFS_SUPER_MAGIC = 0x9123683E
MAX_MANIFEST_BYTES = 4 * 1024 * 1024
SAFE_ENV = {
    "LANG": "C",
    "LC_ALL": "C",
    "PATH": os.environ.get("PATH", ""),
}
LOGGER = logging.getLogger("game_optimization_linux.measure_helper")
_PAIR = re.compile(r'"(?P<key>[^"\\]+)"\s*"(?P<value>(?:[^"\\]|\\.)*)"')
_COMPSIZE_ROW = re.compile(
    r"^\s*(?P<kind>total|none|uncompressed|zstd|zlib|lzo)\s+"
    r"[0-9]+(?:\.[0-9]+)?%\s+"
    r"(?P<disk>[0-9][0-9,]*)\s+"
    r"(?P<uncompressed>[0-9][0-9,]*)\s+"
    r"(?P<referenced>[0-9][0-9,]*)\s*$",
    re.IGNORECASE,
)
_DU_ROW = re.compile(
    r"^\s*(?P<total>\d+)\s+(?P<exclusive>\d+)\s+"
    r"(?P<shared>\d+)\s+.+$"
)


class MeasurementError(RuntimeError):
    pass


def _path_error(code: str, detail: str) -> MeasurementError:
    return MeasurementError(f"{code}: {detail}")


def _log_argv(label: str, argv: list[str]) -> None:
    # argv contains only executable names, validated paths and numeric Steam
    # identifiers.  Polkit credentials and environment data are never logged.
    LOGGER.info("%s argv=%r", label, argv)


class _StatFs(ctypes.Structure):
    _fields_ = [
        ("f_type", ctypes.c_long),
        ("f_bsize", ctypes.c_long),
        ("f_blocks", ctypes.c_ulong),
        ("f_bfree", ctypes.c_ulong),
        ("f_bavail", ctypes.c_ulong),
        ("f_files", ctypes.c_ulong),
        ("f_ffree", ctypes.c_ulong),
        ("f_fsid", ctypes.c_long * 2),
        ("f_namelen", ctypes.c_long),
        ("f_frsize", ctypes.c_long),
        ("f_flags", ctypes.c_long),
        ("f_spare", ctypes.c_long * 4),
    ]


def _json_exit(payload: dict[str, Any], code: int) -> int:
    print(json.dumps(payload, ensure_ascii=False, sort_keys=True))
    return code


def _calling_uid() -> int:
    raw = os.environ.get("PKEXEC_UID", "").strip()
    if not raw.isdecimal():
        raise MeasurementError("PKEXEC_UID is missing")
    uid = int(raw)
    if uid <= 0:
        raise MeasurementError("the calling desktop user is invalid")
    pwd.getpwuid(uid)
    return uid


def _read_manifest(path: Path, uid: int) -> tuple[os.stat_result, dict[str, str]]:
    descriptor = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_CLOEXEC)
    try:
        info = os.fstat(descriptor)
        if not stat.S_ISREG(info.st_mode) or info.st_uid != uid:
            raise MeasurementError("Steam appmanifest ownership or type is invalid")
        if info.st_size > MAX_MANIFEST_BYTES:
            raise MeasurementError("Steam appmanifest is unexpectedly large")
        data = os.read(descriptor, MAX_MANIFEST_BYTES + 1)
    finally:
        os.close(descriptor)
    try:
        text = data.decode("utf-8-sig")
    except UnicodeError as error:
        raise MeasurementError("Steam appmanifest is not valid UTF-8") from error
    values: dict[str, str] = {}
    for match in _PAIR.finditer(text):
        key = match.group("key").casefold()
        value = bytes(match.group("value"), "utf-8").decode("unicode_escape")
        if key in {"appid", "installdir", "buildid", "stateflags"}:
            previous = values.get(key)
            if previous is not None and previous != value:
                raise MeasurementError(f"Steam appmanifest contains conflicting {key}")
            values[key] = value
    return info, values


def _open_game(library: Path, appid: str, buildid: str, uid: int) -> tuple[int, str]:
    if not library.is_absolute() or os.path.normpath(os.fspath(library)) != os.fspath(
        library
    ):
        raise MeasurementError("Steam library path must be normalized and absolute")
    library_info = os.lstat(library)
    if stat.S_ISLNK(library_info.st_mode) or not stat.S_ISDIR(library_info.st_mode):
        raise MeasurementError("Steam library root is not a real directory")
    if library_info.st_uid != uid:
        raise MeasurementError("Steam library root is not owned by the caller")
    manifest = library / "steamapps" / f"appmanifest_{appid}.acf"
    manifest_before, values = _read_manifest(manifest, uid)
    if values.get("appid") != appid or values.get("buildid") != buildid:
        raise _path_error(
            "GAME_PATH_VALIDATION_FAILED",
            "Steam AppID or buildid does not match the manifest",
        )
    install_dir = values.get("installdir", "")
    if (
        not install_dir
        or install_dir in {".", ".."}
        or Path(install_dir).name != install_dir
        or "/" in install_dir
        or "\\" in install_dir
    ):
        raise _path_error(
            "GAME_PATH_VALIDATION_FAILED",
            "Steam installdir is empty or unsafe",
        )

    flags = os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW | os.O_CLOEXEC
    library_fd = os.open(library, flags)
    opened = [library_fd]
    try:
        steamapps_fd = os.open("steamapps", flags, dir_fd=library_fd)
        opened.append(steamapps_fd)
        if os.fstat(steamapps_fd).st_uid != uid:
            raise MeasurementError("Steam steamapps directory is not owned by the caller")
        common_fd = os.open("common", flags, dir_fd=steamapps_fd)
        opened.append(common_fd)
        if os.fstat(common_fd).st_uid != uid:
            raise MeasurementError("Steam common directory is not owned by the caller")
        try:
            game_fd = os.open(install_dir, flags, dir_fd=common_fd)
        except FileNotFoundError as error:
            raise _path_error(
                "GAME_PATH_NOT_FOUND",
                f"Steam game directory {install_dir!r} does not exist",
            ) from error
        except OSError as error:
            raise _path_error(
                "GAME_PATH_VALIDATION_FAILED",
                f"Steam game directory {install_dir!r} could not be opened: {error}",
            ) from error
        opened.append(game_fd)
        game_info = os.fstat(game_fd)
        if game_info.st_uid != uid:
            raise MeasurementError("Steam game directory is not owned by the caller")
        if game_info.st_dev != os.fstat(library_fd).st_dev:
            raise MeasurementError("Steam game crosses the verified library filesystem")
        _require_btrfs(game_fd)
        after = os.stat(manifest, follow_symlinks=False)
        if (
            after.st_dev != manifest_before.st_dev
            or after.st_ino != manifest_before.st_ino
            or after.st_size != manifest_before.st_size
            or after.st_mtime_ns != manifest_before.st_mtime_ns
        ):
            raise MeasurementError("Steam appmanifest changed during verification")
        game_path = _validated_game_path(
            library,
            library / "steamapps" / "common" / install_dir,
            game_fd,
        )
        opened.pop()
        return game_fd, game_path
    finally:
        for descriptor in reversed(opened):
            os.close(descriptor)


def _require_btrfs(descriptor: int) -> None:
    libc = ctypes.CDLL(None, use_errno=True)
    info = _StatFs()
    if libc.fstatfs(descriptor, ctypes.byref(info)) != 0:
        error = ctypes.get_errno()
        raise MeasurementError(f"fstatfs failed: {os.strerror(error)}")
    if int(info.f_type) & 0xFFFFFFFF != BTRFS_SUPER_MAGIC:
        raise MeasurementError("the verified game is not on Btrfs")


def _open_local_game(
    game_path: Path,
    game_id: str,
    expected_device: int,
    expected_inode: int,
    uid: int,
) -> tuple[int, str]:
    if not re.fullmatch(r"[A-Za-z0-9._:-]{1,160}", game_id):
        raise _path_error("GAME_PATH_VALIDATION_FAILED", "local game ID is invalid")
    raw = os.fspath(game_path)
    if (
        not raw.strip()
        or not game_path.is_absolute()
        or os.path.normpath(raw) != raw
    ):
        raise _path_error(
            "GAME_PATH_VALIDATION_FAILED",
            "local game path must be normalized and absolute",
        )
    try:
        path_info = os.lstat(game_path)
        resolved = game_path.resolve(strict=True)
    except FileNotFoundError as error:
        raise _path_error(
            "GAME_PATH_NOT_FOUND", "the selected local game directory does not exist"
        ) from error
    if stat.S_ISLNK(path_info.st_mode) or not stat.S_ISDIR(path_info.st_mode):
        raise _path_error(
            "GAME_PATH_VALIDATION_FAILED", "local game path is not a real directory"
        )
    if resolved != game_path:
        raise _path_error(
            "GAME_PATH_VALIDATION_FAILED", "local game path is not canonical"
        )
    if path_info.st_uid != uid:
        raise _path_error(
            "GAME_PATH_VALIDATION_FAILED",
            "local game directory is not owned by the calling user",
        )
    flags = os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW | os.O_CLOEXEC
    descriptor = os.open(game_path, flags)
    try:
        opened_info = os.fstat(descriptor)
        if (
            opened_info.st_dev != expected_device
            or opened_info.st_ino != expected_inode
            or opened_info.st_dev != path_info.st_dev
            or opened_info.st_ino != path_info.st_ino
        ):
            raise _path_error(
                "GAME_PATH_VALIDATION_FAILED",
                "local game directory identity changed during authorization",
            )
        _require_btrfs(descriptor)
        return descriptor, os.fspath(resolved)
    except BaseException:
        os.close(descriptor)
        raise


def _validated_local_game_path(
    game_path: Path,
    descriptor: int,
    expected_device: int,
    expected_inode: int,
) -> str:
    try:
        resolved = game_path.resolve(strict=True)
        path_info = os.stat(resolved, follow_symlinks=False)
    except FileNotFoundError as error:
        raise _path_error("GAME_PATH_NOT_FOUND", "local game directory disappeared") from error
    descriptor_info = os.fstat(descriptor)
    if (
        resolved != game_path
        or path_info.st_dev != descriptor_info.st_dev
        or path_info.st_ino != descriptor_info.st_ino
        or descriptor_info.st_dev != expected_device
        or descriptor_info.st_ino != expected_inode
    ):
        raise _path_error(
            "GAME_PATH_VALIDATION_FAILED",
            "local game directory no longer matches the authorized directory",
        )
    return os.fspath(resolved)


def _validated_game_path(
    library: Path,
    game_path: Path,
    descriptor: int,
) -> str:
    raw = os.fspath(game_path)
    if not raw.strip():
        raise _path_error("GAME_PATH_VALIDATION_FAILED", "game path is empty")
    if not game_path.is_absolute():
        raise _path_error(
            "GAME_PATH_VALIDATION_FAILED",
            "game path is not absolute",
        )
    try:
        resolved_library = library.resolve(strict=True)
        resolved_game = game_path.resolve(strict=True)
    except FileNotFoundError as error:
        raise _path_error(
            "GAME_PATH_NOT_FOUND",
            f"resolved Steam game path does not exist: {raw}",
        ) from error
    except OSError as error:
        raise _path_error(
            "GAME_PATH_VALIDATION_FAILED",
            f"Steam game path could not be resolved: {error}",
        ) from error
    if not resolved_game.is_dir():
        raise _path_error(
            "GAME_PATH_VALIDATION_FAILED",
            f"resolved Steam game path is not a directory: {resolved_game}",
        )
    try:
        inside_library = (
            os.path.commonpath((resolved_library, resolved_game))
            == os.fspath(resolved_library)
        )
    except ValueError:
        inside_library = False
    if not inside_library:
        raise _path_error(
            "GAME_PATH_VALIDATION_FAILED",
            "resolved game path is outside the verified Steam library",
        )
    path_info = os.stat(resolved_game, follow_symlinks=False)
    descriptor_info = os.fstat(descriptor)
    if (
        path_info.st_dev != descriptor_info.st_dev
        or path_info.st_ino != descriptor_info.st_ino
    ):
        raise _path_error(
            "GAME_PATH_VALIDATION_FAILED",
            "resolved game path no longer matches the verified directory",
        )
    return os.fspath(resolved_game)


def _run(argv: list[str]) -> subprocess.CompletedProcess[str]:
    _log_argv("read-only command", argv)
    return subprocess.run(
        argv,
        stdin=subprocess.DEVNULL,
        capture_output=True,
        text=True,
        check=False,
        timeout=45.0,
        shell=False,
        env=SAFE_ENV,
    )


def _parse_compsize(output: str) -> dict[str, Any]:
    total: tuple[int, int, int] | None = None
    kinds: dict[str, int] = {}
    for line in output.splitlines():
        match = _COMPSIZE_ROW.match(line)
        if match is None:
            continue
        values = tuple(
            int(match.group(name).replace(",", ""))
            for name in ("disk", "uncompressed", "referenced")
        )
        kind = match.group("kind").casefold()
        if kind == "total":
            total = values
        elif kind not in {"none", "uncompressed"}:
            kinds[kind] = values[0]
    if total is None:
        raise MeasurementError("compsize returned an unrecognized report")
    return {
        "disk_usage_bytes": total[0],
        "uncompressed_bytes": total[1],
        "referenced_bytes": total[2],
        "compression_types": kinds,
    }


def _parse_du(output: str) -> dict[str, Any]:
    rows = [match for line in output.splitlines() if (match := _DU_ROW.match(line))]
    if len(rows) != 1:
        raise MeasurementError("btrfs filesystem du returned an unrecognized report")
    match = rows[0]
    total = int(match.group("total"))
    exclusive = int(match.group("exclusive"))
    shared = int(match.group("shared"))
    if exclusive > total or shared > total:
        raise MeasurementError("btrfs filesystem du returned inconsistent totals")
    return {
        "total_bytes": total,
        "exclusive_bytes": exclusive,
        "set_shared_bytes": shared,
        "state": "detected" if shared > 0 or total > exclusive else "not_detected",
    }


def _logical_size(descriptor: int) -> tuple[int, int]:
    root_device = os.fstat(descriptor).st_dev
    total = 0
    files = 0
    for _root, directories, names, directory_fd in os.fwalk(
        f"/proc/self/fd/{descriptor}",
        topdown=True,
        follow_symlinks=False,
    ):
        kept: list[str] = []
        for name in directories:
            try:
                info = os.stat(name, dir_fd=directory_fd, follow_symlinks=False)
            except OSError:
                continue
            if stat.S_ISDIR(info.st_mode) and info.st_dev == root_device:
                kept.append(name)
        directories[:] = kept
        for name in names:
            info = os.stat(name, dir_fd=directory_fd, follow_symlinks=False)
            if stat.S_ISREG(info.st_mode) and info.st_dev == root_device:
                total += max(0, int(info.st_size))
                files += 1
    return total, files


def measure(args: argparse.Namespace) -> dict[str, Any]:
    if not COMPSIZE:
        raise MeasurementError("compsize is not installed")
    if not BTRFS:
        raise MeasurementError("btrfs is not installed")
    uid = _calling_uid()
    local_measurement = bool(getattr(args, "game_path", None))
    if local_measurement:
        game_fd, game_path = _open_local_game(
            Path(args.game_path),
            str(args.game_id),
            int(args.device),
            int(args.inode),
            uid,
        )
    else:
        game_fd, game_path = _open_game(
            Path(args.library),
            str(args.appid),
            str(args.buildid),
            uid,
        )
    try:
        # Revalidate immediately before invoking either external command.  The
        # normal absolute path is passed as one argv item; /proc/self/fd magic
        # links are intentionally not used because compsize may reject them.
        if local_measurement:
            game_path = _validated_local_game_path(
                Path(game_path), game_fd, int(args.device), int(args.inode)
            )
        else:
            game_path = _validated_game_path(
                Path(args.library), Path(game_path), game_fd
            )
        measured_at = datetime.now(UTC).isoformat()
        logical, file_count = _logical_size(game_fd)
        fs = os.fstatvfs(game_fd)
        fragment = int(fs.f_frsize or fs.f_bsize)
        total = int(fs.f_blocks) * fragment
        free = int(fs.f_bfree) * fragment
        available = int(fs.f_bavail) * fragment
        used = max(0, total - free)
        compsize_argv = [
            COMPSIZE,
            "--bytes",
            "--one-file-system",
            game_path,
        ]
        btrfs_du_argv = [
            BTRFS,
            "filesystem",
            "du",
            "--raw",
            "--summarize",
            game_path,
        ]
        compsize = _run(compsize_argv)
        btrfs_du = _run(btrfs_du_argv)
        errors: list[str] = []
        compsize_data: dict[str, Any] | None = None
        du_data: dict[str, Any] | None = None
        if compsize.returncode == 0:
            try:
                compsize_data = _parse_compsize(compsize.stdout)
            except MeasurementError as error:
                errors.append(str(error))
        else:
            errors.append(
                f"compsize exited with status {compsize.returncode}: "
                f"{compsize.stderr.strip()[:500]}"
            )
        if btrfs_du.returncode == 0:
            try:
                du_data = _parse_du(btrfs_du.stdout)
            except MeasurementError as error:
                errors.append(str(error))
        else:
            errors.append(
                f"btrfs filesystem du exited with status {btrfs_du.returncode}: "
                f"{btrfs_du.stderr.strip()[:500]}"
            )
        return {
            "schema_version": 1,
            "ok": compsize_data is not None,
            "measurement_source": "polkit_helper",
            "measurement_error": "; ".join(errors) or None,
            "authorized_uid": uid,
            "identity_kind": "local" if local_measurement else "steam",
            "app_id": "" if local_measurement else str(args.appid),
            "build_id": "" if local_measurement else str(args.buildid),
            "game_id": str(args.game_id) if local_measurement else "",
            "game_path": game_path,
            "path_device": int(os.fstat(game_fd).st_dev),
            "path_inode": int(os.fstat(game_fd).st_ino),
            "measured_at": measured_at,
            "logical_bytes": logical,
            "file_count": file_count,
            "filesystem_total_bytes": total,
            "filesystem_used_bytes": used,
            "filesystem_free_bytes": free,
            "filesystem_available_bytes": available,
            "compsize": compsize_data,
            "btrfs_filesystem_du": du_data,
            "read_only": True,
        }
    finally:
        os.close(game_fd)


def _parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(add_help=False)
    parser.add_argument("operation", choices=("measure", "capability"))
    parser.add_argument("--json", action="store_true")
    parser.add_argument("--library")
    parser.add_argument("--appid")
    parser.add_argument("--buildid")
    parser.add_argument("--game-path")
    parser.add_argument("--game-id")
    parser.add_argument("--device")
    parser.add_argument("--inode")
    return parser


def main(argv: list[str] | None = None) -> int:
    logging.basicConfig(
        level=logging.INFO,
        format="game-optimization-measure-helper: %(message)s",
        stream=sys.stderr,
    )
    try:
        args = _parser().parse_args(argv)
        if args.operation == "capability":
            return _json_exit(
                {
                    "schema_version": 1,
                    "available": bool(COMPSIZE and BTRFS),
                    "compsize_available": bool(COMPSIZE),
                    "btrfs_available": bool(BTRFS),
                    "read_only": True,
                },
                0,
            )
        local_args = (args.game_path, args.game_id, args.device, args.inode)
        steam_args = (args.library, args.appid, args.buildid)
        if any(local_args) and not all(local_args):
            raise MeasurementError(
                "game path, game ID, device and inode are required together"
            )
        if all(local_args) and any(steam_args):
            raise MeasurementError("local and Steam identities cannot be combined")
        if not all(local_args):
            if not all(steam_args):
                raise MeasurementError("library, AppID and buildid are required")
            if not str(args.appid).isdecimal() or not str(args.buildid).isdecimal():
                raise MeasurementError("AppID and buildid must be decimal")
        elif not str(args.device).isdecimal() or not str(args.inode).isdecimal():
            raise MeasurementError("device and inode must be decimal")
        helper_argv = [os.fspath(Path(sys.argv[0]).resolve()), *(argv or sys.argv[1:])]
        _log_argv("helper", helper_argv)
        payload = measure(args)
        return _json_exit(payload, 0 if payload.get("ok") is True else 1)
    except (MeasurementError, OSError, subprocess.SubprocessError) as error:
        return _json_exit(
            {
                "schema_version": 1,
                "ok": False,
                "measurement_source": "polkit_helper",
                "measurement_error": str(error) or type(error).__name__,
                "read_only": True,
            },
            1,
        )


if __name__ == "__main__":
    raise SystemExit(main())
