#!/usr/bin/env python3
"""Root-owned validated netns join + user scope launcher."""

from __future__ import annotations

import importlib.util
import os
import re
import sys

# The activated release is content-addressed. Privileged imports must not add
# interpreter cache files to it after activation.
sys.dont_write_bytecode = True

_BASE = "/usr/local/lib/overdeck"
try:
    with open(f"{_BASE}/seat-authority-active", encoding="ascii") as _fh:
        _version = _fh.read().strip()
except OSError:
    print("overdeck-seat-scope-entry: activation-invalid", file=sys.stderr)
    raise SystemExit(1) from None
if not re.fullmatch(r"[0-9a-f]{64}", _version):
    print("overdeck-seat-scope-entry: activation-invalid", file=sys.stderr)
    raise SystemExit(1)
_OVERDECK_LIB = f"{_BASE}/versions/{_version}"
if not os.path.isdir(_OVERDECK_LIB):
    print("overdeck-seat-scope-entry: activation-invalid", file=sys.stderr)
    raise SystemExit(1)
_MODULE_PATH = os.path.join(_OVERDECK_LIB, "seat_scope_entry.py")
# The wrapper selects the active immutable authority. Keep every module-side installed
# artifact lookup pinned to that same directory, including --install-check.
os.environ["OVERDECK_SEAT_INSTALL_CHECK_ROOT"] = _OVERDECK_LIB


def _load_module():
    if _OVERDECK_LIB not in sys.path:
        sys.path.insert(0, _OVERDECK_LIB)
    spec = importlib.util.spec_from_file_location("seat_scope_entry", _MODULE_PATH)
    if spec is None or spec.loader is None:
        print(f"overdeck-seat-scope-entry: module-missing:{_MODULE_PATH}", file=sys.stderr)
        raise SystemExit(1)
    mod = importlib.util.module_from_spec(spec)
    # dataclass and friends resolve their defining module through sys.modules at class
    # creation time, so a module executed without being registered there fails to load.
    sys.modules[spec.name] = mod
    try:
        spec.loader.exec_module(mod)
    except FileNotFoundError:
        del sys.modules[spec.name]
        print(f"overdeck-seat-scope-entry: module-missing:{_MODULE_PATH}", file=sys.stderr)
        raise SystemExit(1) from None
    return mod


if __name__ == "__main__":
    _load_module().main(sys.argv[1:])
