#!/usr/bin/python3
# Game launch-option prefix wrapper ("armada-game-launch %command%"). Applies
# per-game settings via FEX_APP_CONFIG, the only knob every compat tool's FEX reads
# (the on-disk FEX config files are seen only by the system FEX, not arm64ec/wow64).
import hashlib
import json
import os
import pathlib
import shutil
import socket
import stat
import sys
import time

sys.path.insert(0, "/usr/lib/armada")
import armada_game_tweaks
import armada_perf
import armada_turnip


BASE_FEX_CONFIG = pathlib.Path("/usr/share/fex-emu/Config.json")
FEX_PROFILES_CONFIG = pathlib.Path("/usr/share/armada/fex-profiles.json")
PROTON_INJECT_SRC = pathlib.Path("/usr/share/armada/proton-inject/x86_64-linux-gnu")
SYSTEM_EXEC_PATHS = ("/usr/bin", "/usr/local/bin", "/bin")
# The guest rootfs's stock Turnip, for x86 games; absent on the host, so native loaders skip it.
GUEST_TURNIP_MANIFESTS = (
    "/usr/share/vulkan/icd.d/freedreno_icd.x86_64.json",
    "/usr/share/vulkan/icd.d/freedreno_icd.i686.json",
)
VK_DRIVER_ENV = ("VK_DRIVER_FILES", "VK_ICD_FILENAMES")

def is_appimage(command):
    try:
        fd = os.open(command, os.O_RDONLY | os.O_NONBLOCK | os.O_CLOEXEC)
    except OSError:
        return False
    try:
        if not stat.S_ISREG(os.fstat(fd).st_mode):
            return False
        header = os.read(fd, 11)
    except OSError:
        return False
    finally:
        os.close(fd)

    return (
        len(header) == 11
        and header[:4] == b"\x7fELF"
        and header[8:10] == b"AI"
        and header[10] in (1, 2)
    )


def prepare_appimage_path(args):
    if not any(is_appimage(arg) for arg in args):
        return

    paths = [*SYSTEM_EXEC_PATHS]

    if existing := os.environ.get("PATH"):
        paths.append(existing)

    os.environ["PATH"] = os.pathsep.join(paths)

def appid():
    for key in ("STEAM_COMPAT_APP_ID", "SteamAppId", "SteamGameId"):
        value = os.environ.get(key, "").strip()
        if value.isdigit():
            return value
    return None


def load_fex_contract():
    with FEX_PROFILES_CONFIG.open(encoding="utf-8") as f:
        contract = json.load(f)
    profiles = contract.get("profiles")
    if not isinstance(profiles, dict) or "default" not in profiles:
        raise ValueError("invalid FEX profile contract")
    for profile in profiles.values():
        if not isinstance(profile, dict) or not isinstance(profile.get("config"), dict):
            raise ValueError("invalid FEX profile contract")
    return contract


def thunk_settings(settings, modules):
    thunks = settings.get("thunks")
    if not isinstance(thunks, dict):
        thunks = {}
    return {name: 1 if thunks.get(name, True) else 0 for name in modules}


def cache_dir(name):
    # pressure-vessel shares this cache path into the container; a runtime-dir
    # config is invisible there and FEX silently skips an unseen FEX_APP_CONFIG.
    # Relative XDG_CACHE_HOME (invalid per XDG) would be re-anchored by portable FEX.
    cache = os.environ.get("XDG_CACHE_HOME")
    if cache and pathlib.Path(cache).is_absolute():
        return pathlib.Path(cache) / name
    return pathlib.Path.home() / ".cache" / name


def resolve_fex_config(settings, profiles):
    profile_id = settings.get("fexProfile")
    if isinstance(profile_id, str) and profile_id in profiles:
        return profiles[profile_id]["config"]
    fex_config = settings.get("fexConfig")
    if isinstance(fex_config, dict):
        return fex_config
    return profiles["default"]["config"]


def apply_fex(settings, game_id, profiles, env):
    with BASE_FEX_CONFIG.open(encoding="utf-8") as f:
        config = json.load(f)

    # each FEX resolves rootfs/thunk paths from its own global or template config;
    # forcing Armada's onto the Steam FEX depot (Proton 11) empties its SLR4 rootfs
    for key in ("RootFS", "ThunkGuestLibs", "ThunkHostLibs"):
        config.get("Config", {}).pop(key, None)

    allowed = set().union(*(profile["config"].keys() for profile in profiles.values()))
    fex_config = resolve_fex_config(settings, profiles)
    config.setdefault("Config", {}).update({k: v for k, v in fex_config.items() if k in allowed})
    config["ThunksDB"] = thunk_settings(settings, config.get("ThunksDB", {}).keys())

    config_dir = cache_dir("armada-fex")
    config_dir.mkdir(mode=0o700, parents=True, exist_ok=True)
    cutoff = time.time() - 86400
    for old in config_dir.glob("*.json"):
        try:
            if old.stat().st_mtime < cutoff:
                old.unlink()
        except OSError:
            pass
    name = f"{game_id or 'global'}.{os.getpid()}.json"
    target = config_dir / name
    tmp = target.with_name(f".{name}.tmp")
    try:
        with tmp.open("w", encoding="utf-8") as f:
            json.dump(config, f, indent=2, sort_keys=True)
            f.write("\n")
        os.replace(tmp, target)
        env["FEX_APP_CONFIG"] = str(target)
    finally:
        tmp.unlink(missing_ok=True)


def inject_x86_protocol_libs():
    # pressure-vessel doesn't provide the x86 libwayland-client/libxkbcommon the game
    # needs, so it can't load them (dead controller). Remove once pressure-vessel supplies
    # them.
    if not PROTON_INJECT_SRC.is_dir():
        return
    for tool in os.environ.get("STEAM_COMPAT_TOOL_PATHS", "").split(":"):
        files = pathlib.Path(tool) / "files" if tool else None
        if files is None:
            continue
        lib_dir = files / "lib" / "x86_64-linux-gnu"
        if not lib_dir.is_dir() or (files / "bin-arm64").is_dir():  # skip arm64ec Proton
            continue
        # link targets must be copied before the symlinks that point at them
        for src in sorted(PROTON_INJECT_SRC.iterdir(), key=pathlib.Path.is_symlink):
            dest = lib_dir / src.name
            if dest.exists() or dest.is_symlink():
                continue
            if src.is_symlink():
                os.symlink(os.readlink(src), dest)
            else:
                shutil.copy2(src, dest)


def apply_perf(settings, game_id):
    # env applies last and verbatim so it can override anything the wrapper
    # set, including FEX_APP_CONFIG and the derived WINE_CPU_TOPOLOGY
    clean = armada_perf.sanitize_perf(settings)

    env_extra = settings.get("env")
    if isinstance(env_extra, dict):
        for key, value in env_extra.items():
            if value is None:
                continue
            try:
                os.environ[str(key)] = str(value)
            except (ValueError, OSError) as exc:
                # a malformed name must not abort the rest of the launch path
                print(f"armada-game-launch: bad env entry {key!r}: {exc}", file=sys.stderr)

    cores = clean.get("cores")
    # affinity is always set explicitly (fork inheritance has no reset guard,
    # a restrictive gamescope mask would leak in); under cosmos the scheduler
    # domain replaces the hard mask
    if cores and clean.get("scheduler") != "cosmos":
        os.sched_setaffinity(0, cores)
    else:
        os.sched_setaffinity(0, armada_perf.online_cpus())
    if cores and clean.get("wineTopology", True):
        topology = os.environ.get("PROTON_CPU_TOPOLOGY", os.environ.get(
            "WINE_CPU_TOPOLOGY", f"{len(cores)}:{','.join(map(str, cores))}"))
        os.environ.setdefault("WINE_CPU_TOPOLOGY", topology)
        # PROTON_CPU_TOPOLOGY takes precedence over Proton's per-game defaults.
        os.environ.setdefault("PROTON_CPU_TOPOLOGY", topology)

    nice = clean.get("nice", 0)
    if nice > 0:
        os.setpriority(os.PRIO_PROCESS, 0, nice)

    # the daemon applies negative nice, gamescope overrides and the
    # scheduler; exec preserves the pid so SO_PEERCRED IS the game
    try:
        with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as sock:
            sock.settimeout(3)
            sock.connect(armada_perf.SESSION_SOCKET)
            request = {"action": "game_launched", "appid": game_id or ""}
            sock.sendall((json.dumps(request) + "\n").encode("utf-8"))
            sock.recv(4096)
    except OSError as exc:
        print(f"armada-game-launch: session daemon unavailable: {exc}", file=sys.stderr)


def apply_turnip(settings):
    driver = settings.get("turnipDriver")
    if not isinstance(driver, str) or driver in ("", armada_turnip.STABLE):
        return
    if any(key in os.environ for key in VK_DRIVER_ENV):
        return
    manifests = turnip_manifests(driver)
    # the override replaces driver discovery, so a broken pick would leave no driver
    if not manifests or any(os.pathsep in manifest for manifest in manifests):
        print(f"armada-game-launch: no Turnip driver {driver!r}, using the default",
              file=sys.stderr)
        return
    for key in VK_DRIVER_ENV:
        os.environ[key] = os.pathsep.join(manifests)
    # vkd3d-proton discards its one per-game pipeline cache when the driver changes
    shader_path = pathlib.Path(os.environ.get("STEAM_COMPAT_SHADER_PATH", ""))
    if shader_path.is_absolute() and "VKD3D_SHADER_CACHE_PATH" not in os.environ:
        cache = shader_path / ("vkd3d-" + hashlib.sha256(driver.encode()).hexdigest()[:16])
        try:
            cache.mkdir(parents=True, exist_ok=True)
        except OSError:
            return
        os.environ["VKD3D_SHADER_CACHE_PATH"] = str(cache)


def turnip_manifests(driver):
    if not driver.startswith(armada_turnip.USER_PREFIX):
        return armada_turnip.system_manifests(driver)
    # Driver zips ship a relative-path manifest or none, so the manifest is written here.
    name = driver[len(armada_turnip.USER_PREFIX):]
    library = armada_turnip.user_library(pathlib.Path.home(), name)
    if not library:
        return None
    manifest_dir = cache_dir("armada-turnip")
    manifest_dir.mkdir(mode=0o700, parents=True, exist_ok=True)
    manifest = manifest_dir / f"{name}.json"
    tmp = manifest.with_name(f".{name}.{os.getpid()}.tmp")
    try:
        with tmp.open("w", encoding="utf-8") as f:
            json.dump({"file_format_version": "1.0.1",
                       "ICD": {"library_path": str(library), "api_version": "1.4.0"}}, f)
            f.write("\n")
        os.replace(tmp, manifest)
    finally:
        tmp.unlink(missing_ok=True)
    return [str(manifest), *GUEST_TURNIP_MANIFESTS]


def repair_wedged_controller():
    # x86 Proton can leave the pad registered as a bare USB device, never promoted to
    # WINEXINPUT (dead under x86 too); an arm64ec Proton reusing that prefix then can't
    # re-register it - winebus hits "already exists" (plugplay 0xe000020b) - and inherits
    # the dead pad. Drop the stale VID_28DE sections to re-register.
    data_path = os.environ.get("STEAM_COMPAT_DATA_PATH")
    if not data_path:
        return
    reg = pathlib.Path(data_path) / "pfx" / "system.reg"
    try:
        text = reg.read_text(encoding="utf-8", errors="surrogateescape")
    except FileNotFoundError:
        return
    lines = text.splitlines(keepends=True)
    pad_sections = sum(1 for line in lines if line.startswith("[") and "VID_28DE" in line)
    # Only a WINEXINPUT key for this same pad proves promotion; an old target's keys outlive it.
    promoted = any("WINEXINPUT" in line and "VID_28DE" in line for line in lines)
    if not pad_sections or promoted:
        return  # no pad registered, or it promoted fine - leave the prefix alone
    reg.with_name("system.reg.armada-bak").write_text(
        text, encoding="utf-8", errors="surrogateescape")
    kept, skip = [], False
    for line in lines:
        if line.startswith("["):
            skip = "VID_28DE" in line
        if not skip:
            kept.append(line)
    tmp = reg.with_name(".system.reg.armada-tmp")
    tmp.write_text("".join(kept), encoding="utf-8", errors="surrogateescape")
    os.replace(tmp, reg)
    print(f"armada-game-launch: cleared wedged controller state "
          f"({pad_sections} pad sections)", file=sys.stderr)


def main():
    args = sys.argv[1:]
    if not args:
        raise SystemExit("usage: armada-game-launch COMMAND [ARGS...]")

    # Proton-CachyOS enables its shader compiler HUD unless DXVK_HUD is already
    # set. Keep Armada's default clean while preserving an explicit user HUD.
    os.environ.setdefault("DXVK_HUD", "none")

    game_id = appid()
    settings = {}
    try:
        contract = load_fex_contract()
        settings = armada_game_tweaks.merged_settings(
            armada_game_tweaks.load(), game_id)
        apply_fex(settings, game_id, contract["profiles"], os.environ)
    except Exception as exc:
        print(f"armada-game-launch: failed to apply settings: {exc}", file=sys.stderr)

    prepare_appimage_path(args)

    if not os.environ.get("PATH"):
        os.environ["PATH"] = os.pathsep.join(SYSTEM_EXEC_PATHS)

    try:
        apply_perf(settings, game_id)
    except Exception as exc:
        print(f"armada-game-launch: perf settings skipped: {exc}", file=sys.stderr)

    # after apply_perf so a driver override in the user's env settings wins
    try:
        apply_turnip(settings)
    except Exception as exc:
        print(f"armada-game-launch: Turnip driver skipped: {exc}", file=sys.stderr)

    try:
        inject_x86_protocol_libs()
    except Exception as exc:
        print(f"armada-game-launch: protocol-lib inject skipped: {exc}", file=sys.stderr)

    try:
        repair_wedged_controller()
    except Exception as exc:
        print(f"armada-game-launch: controller repair skipped: {exc}", file=sys.stderr)

    try:
        os.execv(args[0], args)
    except OSError as exc:
        raise SystemExit(f"armada-game-launch: failed to exec game: {exc}")


if __name__ == "__main__":
    main()
