#!/bin/sh
# ElysiOS installer entry — generated by scripts/elysios_install/distribution.py.
# Verifies the signed release index and the installer digest BEFORE anything executes.
set -eu
umask 077

production_origin="https://elysios.ai/updates"
origin_default="https://elysios.ai/updates"
release_public_key_b64="rz3Ex8aVIAbU8CN+PyvURtTyRsdCwyAOg1+ftw/jgVo="

origin="${ELYSIOS_INSTALL_ORIGIN:-$origin_default}"
rehearsal="${ELYSIOS_REHEARSAL:-0}"
requested_channel="${ELYSIOS_INSTALL_CHANNEL:-stable}"
last_accepted_version="${ELYSIOS_LAST_ACCEPTED_VERSION:-}"
production=0
[ "$origin" = "$production_origin" ] && production=1

if [ "$production" = "1" ] && [ "$rehearsal" = "1" ]; then
  printf '%s\n' "The production origin cannot be used as a rehearsal origin." >&2
  exit 1
fi
if [ "$production" = "0" ] && [ "$rehearsal" != "1" ]; then
  printf '%s\n' "Refusing non-production origin without ELYSIOS_REHEARSAL=1." >&2
  exit 1
fi
if [ "$production" = "1" ]; then
  case "$origin" in
    https://*) ;;
    *) printf '%s\n' "The production origin must be HTTPS." >&2; exit 1 ;;
  esac
fi
if [ "$rehearsal" = "1" ]; then
  printf '%s\n' "=== ELYSIOS UNSIGNED REHEARSAL — this is not a release and installs staged, unsigned artifacts ===" >&2
fi

tenant="${1:-}"
if [ -z "$tenant" ]; then
  if [ -t 0 ]; then
    printf '%s\n' "Enter the business name for this ElysiOS:" >&2
    IFS= read -r tenant || true
  fi
  if [ -z "$tenant" ]; then
    printf '%s\n' "A business name is required." >&2
    exit 2
  fi
fi

# --- platform dispatch (design §5): derive one key from both host facts. ---
uname_s="$(uname -s 2>/dev/null || echo unknown)"
uname_m="$(uname -m 2>/dev/null || echo unknown)"
case "$uname_s" in
  Darwin)
    case "$uname_m" in
      arm64|aarch64) platform_key="darwin-arm64" ;;
      *) printf '%s\n' "ElysiOS installs on Apple Silicon Macs; this Mac reports '$uname_m'. No installer was fetched." >&2; exit 1 ;;
    esac ;;
  Linux)
    case "$uname_m" in
      x86_64|amd64) platform_key="linux-x86_64" ;;
      aarch64|arm64) platform_key="linux-arm64" ;;
      *) printf '%s\n' "ElysiOS installs on x86_64 or arm64 Linux; this computer reports '$uname_m'. No installer was fetched." >&2; exit 1 ;;
    esac ;;
  MINGW*|MSYS*|CYGWIN*)
    case "$uname_m" in
      x86_64|amd64) platform_key="windows-x86_64" ;;
      *) printf '%s\n' "ElysiOS installs on x86_64 Windows; this computer reports '$uname_m'. No installer was fetched." >&2; exit 1 ;;
    esac ;;
  *) printf '%s\n' "ElysiOS does not have an installer for this operating system ('$uname_s'). No installer was fetched." >&2; exit 1 ;;
esac

if [ "$platform_key" = "windows-x86_64" ]; then
  printf '%s\n' "ElysiOS is not available on this Windows computer yet. Nothing has been downloaded or installed." >&2
  exit 1
fi

gui_session() {
  command -v open >/dev/null 2>&1 || return 1
  manager=""
  if command -v launchctl >/dev/null 2>&1; then
    manager="$(launchctl managername 2>/dev/null || true)"
  fi
  [ "$manager" = "Aqua" ]
}

# A Mac installs by opening the signed disk image in its desktop session. Without one there is
# nothing to open it in, so refuse before a single byte is fetched.
if [ "$platform_key" = "darwin-arm64" ] && ! gui_session; then
  printf '%s\n' "This Mac has no desktop session to open the ElysiOS disk image in. Nothing was downloaded or installed on this Mac." >&2
  printf '%s\n' "Run this again from Terminal while signed in at the Mac's display." >&2
  exit 1
fi

python3=""
if command -v python3 >/dev/null 2>&1; then
  python3="$(command -v python3)"
else
  printf '%s\n' "python3 is required to verify the ElysiOS release index (present on every Ubuntu VPS image)." >&2
  exit 1
fi

fetch=""
if command -v curl >/dev/null 2>&1; then
  fetch="curl -fsSL"
elif command -v wget >/dev/null 2>&1; then
  fetch="wget -qO-"
else
  printf '%s\n' "curl or wget is required to fetch the ElysiOS installer." >&2
  exit 1
fi

work="$(mktemp -d "${TMPDIR:-/tmp}/elysios-fetch.XXXXXX")"
preserve_work=0
cleanup() { [ "$preserve_work" = "1" ] || rm -rf "$work"; }
trap cleanup EXIT INT TERM

printf '%s\n' "Fetching the ElysiOS release index from $origin ..." >&2
$fetch "$origin/releases/index.json" >"$work/index.json"
$fetch "$origin/releases/index.signature.json" >"$work/index.signature.json"

cat >"$work/verify-index.py" <<'ELYSIOS_VERIFY_PY'
from __future__ import annotations
_Q = 2**255 - 19
_L = 2**252 + 27742317777372353535851937790883648493
_D = -121665 * pow(121666, _Q - 2, _Q) % _Q


def _sha512(data):
    import hashlib
    return hashlib.sha512(data).digest()


def _sha512_int(data):
    return int.from_bytes(_sha512(data), "little")


_IDENT = (0, 1, 1, 0)


def _point_add(p, q):
    a = (p[1] - p[0]) * (q[1] - q[0]) % _Q
    b = (p[1] + p[0]) * (q[1] + q[0]) % _Q
    c = 2 * p[3] * q[3] * _D % _Q
    d = 2 * p[2] * q[2] % _Q
    e, f, g, h = b - a, d - c, d + c, b + a
    return (e * f % _Q, g * h % _Q, f * g % _Q, e * h % _Q)


def _point_mul(s, p):
    q = _IDENT
    while s > 0:
        if s & 1:
            q = _point_add(q, p)
        p = _point_add(p, p)
        s >>= 1
    return q


def _point_equal(p, q):
    return ((p[0] * q[2] - q[0] * p[2]) % _Q == 0
            and (p[1] * q[2] - q[1] * p[2]) % _Q == 0)


_BY = 4 * pow(5, _Q - 2, _Q) % _Q


def _recover_x(y, sign):
    if y >= _Q:
        return None
    x2 = (y * y - 1) * pow(_D * y * y + 1, _Q - 2, _Q) % _Q
    if x2 == 0:
        return None if sign else 0
    x = pow(x2, (_Q + 3) // 8, _Q)
    if (x * x - x2) % _Q != 0:
        x = x * pow(2, (_Q - 1) // 4, _Q) % _Q
    if (x * x - x2) % _Q != 0:
        return None
    if (x & 1) != sign:
        x = _Q - x
    return x


_BX = _recover_x(_BY, 0)
_B = (_BX, _BY, 1, _BX * _BY % _Q)


def _point_decompress(data):
    if len(data) != 32:
        return None
    y = int.from_bytes(data, "little")
    sign = y >> 255
    y &= (1 << 255) - 1
    x = _recover_x(y, sign)
    if x is None:
        return None
    return (x, y, 1, x * y % _Q)


def _verify(pub, message, signature):
    if len(pub) != 32 or len(signature) != 64:
        return False
    a_point = _point_decompress(pub)
    if a_point is None:
        return False
    r_bytes, s_bytes = signature[:32], signature[32:]
    r_point = _point_decompress(r_bytes)
    if r_point is None:
        return False
    s = int.from_bytes(s_bytes, "little")
    if s >= _L:
        return False
    k = _sha512_int(r_bytes + pub + message) % _L
    left = _point_mul(8 * s, _B)
    right = _point_add(_point_mul(8, r_point), _point_mul(8 * k, a_point))
    return _point_equal(left, right)



def payload_unsigned(payload):
    return bool(payload.get("unsigned"))


import json
import re
_VERSION = re.compile('v?([0-9]+(?:\\.[0-9]+)*)')
_LEGACY_VERSION = re.compile('[0-9a-f]{12}')
LEGACY_VERSION_FLOOR = '1.12065'
_CHANNEL = re.compile('[a-z][a-z0-9-]{0,31}')
class DistributionError(RuntimeError): pass
import os
import stat
from pathlib import Path
INSTALL_TRUST_DIR = '.elysios-install-trust'
INSTALL_TRUST_FILE = 'accepted.json'
INSTALL_TRUST_RECOVERY = 'ElysiOS cannot confirm which version is installed. Restore your ElysiOS installation from your private backup, or contact ElysiOS support for recovery, then run the installer again.'
class _DuplicateJSONKeyError(ValueError):
    """An authenticated JSON object contains ambiguous exact or case-folded keys."""


def _fold_json_key(key: str) -> str:
    """Fold the whole key, including multi-character Unicode case expansions."""
    return key.casefold()


def _load_json_rejecting_duplicates(raw: bytes | str):
    """Decode JSON with duplicate-key rejection at every object depth."""
    def unique_object(pairs: list[tuple[str, object]]) -> dict:
        result: dict[str, object] = {}
        seen: set[str] = set()
        for key, value in pairs:
            folded = _fold_json_key(key)
            if folded in seen:
                raise _DuplicateJSONKeyError(f"duplicate JSON key: {key}")
            seen.add(folded)
            result[key] = value
        return result

    return json.loads(raw, object_pairs_hook=unique_object)


def _reject_json_case_aliases(value) -> None:
    """Reject ambiguity in already-decoded inputs before schema or trust dispatch."""
    if isinstance(value, dict):
        seen: set[str] = set()
        for key, child in value.items():
            if isinstance(key, str):
                folded = _fold_json_key(key)
                if folded in seen:
                    raise _DuplicateJSONKeyError(f"duplicate JSON key: {key}")
                seen.add(folded)
            _reject_json_case_aliases(child)
    elif isinstance(value, list):
        for child in value:
            _reject_json_case_aliases(child)


def _version_components(version: str) -> tuple[int, ...] | None:
    # A SHA can consist entirely of decimal digits; it is still a legacy identity,
    # not an enormous orderable release that may jump over the migration floor.
    if _LEGACY_VERSION.fullmatch(version):
        return None
    match = _VERSION.fullmatch(version)
    if not match:
        return None
    return tuple(int(component) for component in match.group(1).split("."))


def _version_is_older(version: str, accepted: str) -> bool:
    if not isinstance(version, str) or not isinstance(accepted, str):
        return True
    current_parts = _version_components(version)
    accepted_parts = _version_components(accepted)
    if current_parts is None or accepted_parts is None:
        # An unorderable version cannot prove that it meets the caller's lower bound.
        return True
    width = max(len(current_parts), len(accepted_parts))
    return current_parts + (0,) * (width - len(current_parts)) < accepted_parts + (0,) * (width - len(accepted_parts))


def _parse_sidecar_json(raw: bytes | str) -> dict:
    """Parse a sidecar while rejecting duplicate object keys at every level."""
    try:
        value = _load_json_rejecting_duplicates(raw)
    except _DuplicateJSONKeyError as exc:
        raise DistributionError(str(exc)) from exc
    if not isinstance(value, dict):
        raise ValueError("sidecar document must be an object")
    return value


def _enforce_index_policy(payload: dict, *, requested_channel: str,
                          last_accepted_version: str | None) -> None:
    if not isinstance(requested_channel, str) or not _CHANNEL.fullmatch(requested_channel):
        raise DistributionError("release index trust policy refused: requested channel is invalid")
    if payload.get("channel") != requested_channel:
        raise DistributionError("release index trust policy refused: requested channel differs")
    if last_accepted_version is not None and _version_is_older(
            payload.get("version"), last_accepted_version):
        raise DistributionError("release index trust policy refused: release is older than last accepted version")


def _install_owner_home() -> Path:
    if os.environ.get("ELYSIOS_INSTALLED_RUNTIME") == "1" or os.environ.get("ELYSIOS_CUSTOMER_SERVICE") == "1":
        account = os.environ.get("ELYSIOS_ACCOUNT_HOME")
        if not account or not Path(account).is_absolute():
            raise DistributionError("install trust state has no owner account binding")
        return Path(account)
    return Path.home()


def _install_trust_root() -> Path:
    return _install_owner_home() / INSTALL_TRUST_DIR


def _private_descriptor(descriptor: int, *, directory: bool) -> None:
    info = os.fstat(descriptor)
    expected = 0o700 if directory else 0o600
    kind = stat.S_ISDIR if directory else stat.S_ISREG
    if (not kind(info.st_mode) or stat.S_IMODE(info.st_mode) != expected
            or info.st_uid != os.geteuid() or (not directory and info.st_nlink != 1)):
        raise DistributionError("install trust state is not owner-only")


def _open_trust_root(root: Path) -> int:
    descriptor = os.open(root, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW | getattr(os, "O_BINARY", 0))
    try:
        _private_descriptor(descriptor, directory=True)
    except BaseException:
        os.close(descriptor)
        raise
    return descriptor


def _read_accepted_version(directory: int, public_key: bytes, channel: str) -> str:
    descriptor = os.open(INSTALL_TRUST_FILE, os.O_RDONLY | os.O_NOFOLLOW | getattr(os, "O_BINARY", 0), dir_fd=directory)
    try:
        _private_descriptor(descriptor, directory=False)
        raw = os.read(descriptor, 4097)
    finally:
        os.close(descriptor)
    if len(raw) > 4096:
        raise DistributionError("install trust state is malformed")
    document = _load_json_rejecting_duplicates(raw)
    if (not isinstance(document, dict)
            or set(document) != {"schema", "authority", "channel", "version"}
            or document.get("schema") != "elysios.install-trust/v1"
            or document.get("authority") != base64.b64encode(public_key).decode("ascii")
            or document.get("channel") != channel
            or not isinstance(document.get("version"), str)
            or _version_components(document["version"]) is None):
        raise DistributionError("install trust state is malformed or belongs to another authority/channel")
    return document["version"]


def _stronger_version(stored: str | None, proposed: str | None) -> str | None:
    if proposed is not None and (not isinstance(proposed, str) or _version_components(proposed) is None):
        raise DistributionError("install trust version floor is malformed")
    if stored is None:
        return proposed
    return proposed if proposed is not None and _version_is_older(stored, proposed) else stored


def _installed_release_version() -> str:
    """Recover only from the installed receipt the updater advances with activation."""
    try:
        directory = _open_trust_root(_install_owner_home() / ".elysios")
        try:
            descriptor = os.open("install-receipt.json", os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK | getattr(os, "O_BINARY", 0),
                                 dir_fd=directory)
            try:
                before = os.fstat(descriptor)
                if (not stat.S_ISREG(before.st_mode) or before.st_uid != os.geteuid()
                        or before.st_nlink != 1 or stat.S_IMODE(before.st_mode) & 0o077
                        or not before.st_mode & stat.S_IRUSR or not 0 < before.st_size <= 65_536):
                    raise ValueError("installed receipt is not a bounded owner-only file")
                raw = bytearray()
                while chunk := os.read(descriptor, min(65_537 - len(raw), 65_536)):
                    raw.extend(chunk)
                    if len(raw) > 65_536:
                        raise ValueError("installed receipt exceeds its byte bound")
                after = os.fstat(descriptor)
                current = os.stat("install-receipt.json", dir_fd=directory, follow_symlinks=False)
                identity = lambda item: (item.st_dev, item.st_ino, item.st_mode, item.st_uid,
                    item.st_nlink, item.st_size, item.st_mtime_ns, item.st_ctime_ns)
                if identity(before) != identity(after) or identity(after) != identity(current) or len(raw) != after.st_size:
                    raise ValueError("installed receipt changed while being read")
            finally:
                os.close(descriptor)
        finally:
            os.close(directory)
        document = _load_json_rejecting_duplicates(bytes(raw))
        if (not isinstance(document, dict) or document.get("schema") != "elysios.install-receipt.v1"
                or not isinstance(document.get("package_version"), str)):
            raise ValueError("installed receipt has no orderable installed version")
        # All descriptor, race, size, owner, schema and duplicate-key checks above
        # also govern this one-time bridge from the old package identity format.
        if _LEGACY_VERSION.fullmatch(document["package_version"]):
            return LEGACY_VERSION_FLOOR
        if _version_components(document["package_version"]) is None:
            raise ValueError("installed receipt has no orderable installed version")
        return document["package_version"]
    except (OSError, ValueError, DistributionError) as exc:
        raise DistributionError(INSTALL_TRUST_RECOVERY) from exc


def _recover_accepted_version(proposed: str | None) -> str | None:
    """Read the installed floor without changing owner trust state."""
    return _stronger_version(_installed_release_version(), proposed)


def _accepted_version_floor(public_key: bytes, channel: str, proposed: str | None = None) -> str | None:
    if len(public_key) != 32 or not isinstance(channel, str) or not _CHANNEL.fullmatch(channel):
        raise DistributionError("install trust authority/channel is invalid")
    _stronger_version(None, proposed)
    root = _install_trust_root()
    try:
        directory = _open_trust_root(root)
    except FileNotFoundError as exc:
        if os.path.lexists(root):
            raise DistributionError(INSTALL_TRUST_RECOVERY) from exc
        if os.path.lexists(_install_owner_home() / ".elysios"):
            return _recover_accepted_version(proposed)
        # First-use trust requires both the trust root and customer installation absent.
        return _stronger_version(None, proposed)
    except OSError as exc:
        if root.is_symlink():
            raise DistributionError(INSTALL_TRUST_RECOVERY) from exc
        raise DistributionError("install trust state is unreadable") from exc
    try:
        stored = _read_accepted_version(directory, public_key, channel)
    except FileNotFoundError:
        stored = None
    except (OSError, ValueError) as exc:
        raise DistributionError("install trust state is missing, unreadable or malformed") from exc
    finally:
        os.close(directory)
    if stored is None:
        return _recover_accepted_version(proposed)
    return _stronger_version(stored, proposed)


def _record_accepted_version(version: str, public_key: bytes, channel: str, *, first_use: bool) -> None:
    import fcntl
    if len(public_key) != 32 or not isinstance(version, str) or _version_components(version) is None:
        raise DistributionError("accepted release identity/version is invalid")
    root = _install_trust_root()
    created = False
    if first_use:
        try:
            root.mkdir(mode=0o700)
            created = True
        except FileExistsError:
            pass
    try:
        directory = _open_trust_root(root)
        try:
            # Lock the stable directory inode; all writers re-read the floor under it.
            fcntl.flock(directory, fcntl.LOCK_EX)
            try:
                floor = _read_accepted_version(directory, public_key, channel)
            except FileNotFoundError:
                if os.path.lexists(_install_owner_home() / ".elysios"):
                    # Only this post-success writer may initialize recovered trust state.
                    floor = _installed_release_version()
                elif created:
                    floor = None
                else:
                    raise
            if floor is not None and _version_is_older(version, floor):
                raise DistributionError("accepted release is older than the stored install trust floor")
            document = {"schema": "elysios.install-trust/v1",
                "authority": base64.b64encode(public_key).decode("ascii"), "channel": channel, "version": version}
            temporary = ".accepted-" + os.urandom(16).hex()
            descriptor = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW | getattr(os, "O_BINARY", 0),
                                 0o600, dir_fd=directory)
            temporary_exists = True
            try:
                os.fchmod(descriptor, 0o600)
                with os.fdopen(descriptor, "w", encoding="utf-8") as handle:
                    json.dump(document, handle, sort_keys=True)
                    handle.flush()
                    os.fsync(handle.fileno())
                os.replace(temporary, INSTALL_TRUST_FILE, src_dir_fd=directory, dst_dir_fd=directory)
                temporary_exists = False
                os.fsync(directory)
            finally:
                if temporary_exists:
                    os.unlink(temporary, dir_fd=directory)
        finally:
            os.close(directory)
    except (OSError, ValueError) as exc:
        raise DistributionError("accepted install trust state could not be persisted") from exc


import base64
import json
import re
import platform
import sys

index_path, signature_path, key_b64, production = (
    sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4],
)
platform_key = sys.argv[5] if len(sys.argv) > 5 else ""
if not platform_key:
    # No dispatcher supplied a selection: this is a Linux host asking for its own
    # architecture, so derive it rather than assume x86_64.
    machine = platform.machine().strip().lower()
    if machine in {"x86_64", "amd64"}:
        platform_key = "linux-x86_64"
    elif machine in {"aarch64", "arm64"}:
        platform_key = "linux-arm64"
    else:
        print("unsupported Linux installer architecture " + machine, file=sys.stderr)
        raise SystemExit(1)
try:
    index_payload = _load_json_rejecting_duplicates(open(index_path, "r", encoding="utf-8").read())
    signature_object = _load_json_rejecting_duplicates(open(signature_path, "r", encoding="utf-8").read())
except (OSError, ValueError) as exc:
    print("release index could not be read: %s" % exc, file=sys.stderr)
    raise SystemExit(1)
if not isinstance(index_payload, dict) or not isinstance(signature_object, dict):
    print("release index document is malformed", file=sys.stderr)
    raise SystemExit(1)
encoded = signature_object.get("value_b64")
if signature_object.get("algorithm") != "Ed25519" or not isinstance(encoded, str) or not encoded:
    print("release index signature is missing or malformed", file=sys.stderr)
    raise SystemExit(1)
if index_payload.get("schema") != "elysios.distribution-index/v1":
    print("release index schema is unsupported", file=sys.stderr)
    raise SystemExit(1)
try:
    public_key = base64.b64decode(key_b64, validate=True)
    signature = base64.b64decode(encoded, validate=True)
except (ValueError, TypeError):
    print("release key or signature is malformed", file=sys.stderr)
    raise SystemExit(1)
authority = index_payload.get("authority")
expected_authority = {
    "algorithm": "Ed25519",
    "public_key_b64": key_b64,
}
if authority != expected_authority:
    print("release index authority differs from the pinned release public key", file=sys.stderr)
    raise SystemExit(1)
canonical = json.dumps(index_payload, sort_keys=True, separators=(",", ":")).encode("utf-8")
if not _verify(public_key, canonical, signature):
    print("release index is not signed by the release authority", file=sys.stderr)
    raise SystemExit(1)
try:
    requested_channel = sys.argv[6] if len(sys.argv) > 6 else "stable"
    proposed = (sys.argv[7] or None) if len(sys.argv) > 7 else None
    recording_first_use = len(sys.argv) > 9 and sys.argv[8] == "record" and sys.argv[9] == "1" and not os.path.lexists(_install_trust_root())
    accepted_floor = _stronger_version(None, proposed) if recording_first_use else _accepted_version_floor(public_key, requested_channel, proposed)
    first_use = not os.path.lexists(_install_trust_root())
    _enforce_index_policy(index_payload,
        requested_channel=sys.argv[6] if len(sys.argv) > 6 else "stable",
        last_accepted_version=accepted_floor)
except DistributionError as exc:
    print(str(exc), file=sys.stderr)
    raise SystemExit(1)
if not index_payload.get("unsigned") and (not isinstance(index_payload.get("version"), str) or _version_components(index_payload["version"]) is None):
    print("signed release version is not orderable for install trust state", file=sys.stderr)
    raise SystemExit(1)
if len(sys.argv) > 8 and sys.argv[8] == "record":
    try:
        _record_accepted_version(index_payload["version"], public_key, requested_channel,
            first_use=sys.argv[9] == "1" if len(sys.argv) > 9 else first_use)
    except DistributionError as exc:
        print(str(exc), file=sys.stderr)
        raise SystemExit(1)
    raise SystemExit(0)
print("FIRST_USE=" + ("1" if first_use else "0"))
entry = index_payload.get("platforms", {}).get(platform_key)
if not isinstance(entry, dict):
    if platform_key == "darwin-arm64":
        print(
            "release index has no darwin-arm64 platform entry; the macOS installer is a "
            "signed disk image and is never fetched as the Linux .run",
            file=sys.stderr,
        )
    else:
        print("release index has no " + platform_key + " platform entry", file=sys.stderr)
    raise SystemExit(1)
name, digest = entry.get("installer"), entry.get("sha256")
if not isinstance(name, str) or not re.fullmatch(r"[A-Za-z0-9._-]{1,128}", name):
    print("release index installer name is invalid", file=sys.stderr)
    raise SystemExit(1)
if not isinstance(digest, str) or not re.fullmatch(r"[0-9a-f]{64}", digest):
    print("release index installer digest is invalid", file=sys.stderr)
    raise SystemExit(1)
size_bytes = None
raw_size = entry.get("size_bytes")
if platform_key == "darwin-arm64" or raw_size is not None:
    # The disk image entry must carry its signed size; any other entry that carries one is
    # held to it before the installer runs.
    if isinstance(raw_size, bool) or not isinstance(raw_size, int) or raw_size < 0:
        if platform_key == "darwin-arm64":
            print("release index darwin size is invalid", file=sys.stderr)
        else:
            print("release index installer size is invalid", file=sys.stderr)
        raise SystemExit(1)
    size_bytes = raw_size
headless_keys = (
    "headless_installer", "headless_sha256", "headless_size_bytes",
    "headless_sidecar", "headless_sidecar_sha256",
)
if any(key in entry for key in headless_keys):
    headless_name, headless_digest, headless_size, headless_sidecar_name, headless_sidecar_digest = (
        entry.get(key) for key in headless_keys
    )
    if (
        any(entry.get(key) is None for key in headless_keys)
        or not isinstance(headless_name, str) or not headless_name.endswith(".run")
        or not re.fullmatch(r"[A-Za-z0-9._-]{1,128}", headless_name)
        or not isinstance(headless_digest, str) or not re.fullmatch(r"[0-9a-f]{64}", headless_digest)
        or isinstance(headless_size, bool) or not isinstance(headless_size, int) or headless_size <= 0
        or not isinstance(headless_sidecar_name, str)
        or not re.fullmatch(r"[A-Za-z0-9._-]{1,128}", headless_sidecar_name)
        or not isinstance(headless_sidecar_digest, str)
        or not re.fullmatch(r"[0-9a-f]{64}", headless_sidecar_digest)
        or not name.endswith(".deb")
    ):
        print("release index headless installer is invalid", file=sys.stderr)
        raise SystemExit(1)
    name, digest, size_bytes = headless_name, headless_digest, headless_size
if name.endswith(".deb"):
    print(
        "release index Linux desktop package cannot be executed directly; headless installer is missing",
        file=sys.stderr,
    )
    raise SystemExit(1)
if payload_unsigned(index_payload) and production == "1":
    print(
        "the release index is marked unsigned and may never be served from the production "
        "origin; refusing to install",
        file=sys.stderr,
    )
    raise SystemExit(1)
if not payload_unsigned(index_payload) and name.startswith("Install-ElysiOS-UNSIGNED"):
    print(
        "release index inconsistency: unsigned-named installer on a signed release index",
        file=sys.stderr,
    )
    raise SystemExit(1)
print("PLATFORM=" + platform_key)
print("INSTALLER=" + name)
print("SHA256=" + digest)
if size_bytes is not None:
    print("SIZE_BYTES=" + str(size_bytes))
print("UNSIGNED=" + ("1" if payload_unsigned(index_payload) else "0"))

ELYSIOS_VERIFY_PY

verify_output="$($python3 "$work/verify-index.py" "$work/index.json" "$work/index.signature.json" "$release_public_key_b64" "$production" "$platform_key" "$requested_channel" "$last_accepted_version")" || exit 1

eval "$verify_output"
if [ "${UNSIGNED:-1}" = "1" ]; then
  if [ "$production" = "1" ]; then
    printf '%s\n' "The release index is marked unsigned; refusing to install from the production origin." >&2
    exit 1
  fi
  printf '%s\n' "=== UNSIGNED installer: this ElysiOS artifact is a rehearsal, not a release ===" >&2
fi

# The index signature is verified and this host's platform entry is selected: the read is
# proven before a single installer byte is fetched.  This is the stage release.yml asserts.
printf '%s\n' "release read verified: platform=$PLATFORM installer=$INSTALLER" >&2

printf '%s\n' "Downloading $INSTALLER ..." >&2
$fetch "$origin/releases/$INSTALLER" >"$work/$INSTALLER"
if [ "$PLATFORM" = "darwin-arm64" ]; then
  if command -v shasum >/dev/null 2>&1; then
    actual="$(shasum -a 256 "$work/$INSTALLER" | awk '{print $1}')"
  elif command -v sha256sum >/dev/null 2>&1; then
    actual="$(sha256sum "$work/$INSTALLER" | awk '{print $1}')"
  else
    printf '%s\n' "Need shasum (stock macOS) or sha256sum to verify the disk image." >&2
    exit 1
  fi
else
  actual="$(sha256sum "$work/$INSTALLER" | awk '{print $1}')"
fi
if [ "$actual" != "$SHA256" ]; then
  printf '%s\n' "Fetched installer bytes do not match the signed release index; refusing to install." >&2
  exit 1
fi
if [ -n "${SIZE_BYTES:-}" ]; then
  actual_size="$(wc -c < "$work/$INSTALLER" | awk '{print $1}')"
  if [ "$actual_size" != "$SIZE_BYTES" ]; then
    printf '%s\n' "Fetched installer size $actual_size does not match the signed release index size $SIZE_BYTES; refusing to install." >&2
    exit 1
  fi
fi
printf '%s\n' "sha256 ok" >&2

if [ "$PLATFORM" = "darwin-arm64" ]; then
  # The owner opens a signed, notarized, stapled disk image; Finder and Gatekeeper mount it.
  # install.sh never execs DMG contents and never runs a host-Python ABI gate on macOS (§5, Q2).
  if gui_session; then
    printf '%s\n' "Opening the ElysiOS disk image for \"$tenant\" — Gatekeeper will check the Apple staple." >&2
    # Keep the verified source available while Finder mounts it from its original path.
    preserve_work=1
    open "$work/$INSTALLER"
    if [ "$UNSIGNED" = "0" ]; then
      $python3 "$work/verify-index.py" "$work/index.json" "$work/index.signature.json" "$release_public_key_b64" "$production" "$platform_key" "$requested_channel" "$last_accepted_version" record "$FIRST_USE"
    fi
    exit 0
  fi
  preserve_work=1
  printf '%s\n' "No GUI session: refusing to open the disk image; nothing was installed on this Mac." >&2
  printf '%s\n' "Verified macOS installer: $work/$INSTALLER" >&2
  printf '%s\n' "Open this disk image on a Mac with a display; Gatekeeper will verify the Apple staple." >&2
  exit 1
fi

chmod 0755 "$work/$INSTALLER"

printf '%s\n' "Running the ElysiOS installer for \"$tenant\" ..." >&2
"$work/$INSTALLER" "$tenant"
if [ "$UNSIGNED" = "0" ]; then
  $python3 "$work/verify-index.py" "$work/index.json" "$work/index.signature.json" "$release_public_key_b64" "$production" "$platform_key" "$requested_channel" "$last_accepted_version" record "$FIRST_USE"
fi
