#!/usr/bin/env python3
"""Stage a trusted local native release and invoke its existing delivery helper.

Standalone Python standard library only; no download or build. Host preparation
uses a separate approval and the same archive-pinned packaged helper.
The SHA256 must come from an independently trusted release channel. Planning
uses disposable public staging only. Apply needs explicit approval and root;
the packaged backend retains all host, backup, migration and readiness gates.
"""
import argparse
import hashlib
import json
import os
from pathlib import Path, PurePosixPath
import re
import signal
import stat
import subprocess
import sys
import tarfile
import tempfile

ARCHIVE_LIMIT = 512 * 1024**2
HELPER_LIMIT = 1024**2
PROFILE_LIMIT = 4096
HELPER_NAME = "tools/delivery-helper.py"
PROFILE_FIELDS = {"format", "environment", "hostname", "address", "origin"}
PROXY_PROFILE_FIELDS = PROFILE_FIELDS | {"web_mode", "trusted_proxy_address"}


class StageError(Exception):
    """Fail closed without disclosing input contents."""


class PackagedDeliveryStopped(StageError):
    """The child already emitted its safe phase/reason; do not append text."""


def terminal_failure(machine_message):
    # The downloaded launcher is standalone: do not import adjacent modules.
    if sys.stdout.isatty() and sys.stderr.isatty():
        return ("Nasazení nebylo dokončeno. Ověřte balíček, profil a poslední zobrazený krok.\n"
                "Zachovejte záznamy; neopakujte operaci ani nemažte ochranný stav naslepo.")
    return json.dumps({"status": "failed", "phase": "release-staging", "reason": "staging-verification-failed",
                       "next": "preserve-evidence-and-investigate-no-automatic-retry"}, sort_keys=True)


def require(condition, message):
    if not condition:
        raise StageError(message)


def public_json(content):
    def unique(pairs):
        result = {}
        for key, value in pairs:
            require(key not in result, "Duplicate public JSON field")
            result[key] = value
        return result
    return json.loads(content, object_pairs_hook=unique)


def snapshot(source, destination, limit, expected=None):
    """Copy a no-follow regular descriptor, never reopen caller-controlled bytes."""
    descriptor = os.open(source, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK)
    value = hashlib.sha256()
    with os.fdopen(descriptor, "rb") as incoming:
        info = os.fstat(incoming.fileno())
        require(stat.S_ISREG(info.st_mode) and info.st_nlink == 1 and
                0 < info.st_size <= limit, "Unsafe public source metadata")
        with destination.open("xb") as outgoing:
            remaining = limit
            while chunk := incoming.read(min(1024**2, remaining + 1)):
                remaining -= len(chunk)
                require(remaining >= 0, "Public source exceeded staging limit")
                value.update(chunk)
                outgoing.write(chunk)
            outgoing.flush()
            os.fsync(outgoing.fileno())
            os.fchmod(outgoing.fileno(), 0o400)
    require(expected is None or value.hexdigest() == expected, "Native archive checksum differs")


def staging_parent():
    # Ignore TMPDIR. Root / and fixed sticky /tmp prevent another UID replacing
    # the exclusive private directory; apply must create it as root itself.
    for path in (Path("/"), Path("/tmp")):
        info = path.lstat()
        require(stat.S_ISDIR(info.st_mode) and info.st_uid == 0 and
                (stat.S_IMODE(info.st_mode) == 0o1777 if path == Path("/tmp")
                 else not info.st_mode & 0o022), "Unsafe release staging parent")
    return Path("/tmp")


def helper_bytes(path):
    """Minimal bootstrap validation; full format validation stays in the helper.

    Authentication precedes this parser. Never extract the archive tree or trust
    tar extension metadata, links, duplicate names, traversal or private paths.
    """
    seen = set()
    total = 0
    helper = manifest = None
    with tarfile.open(path, "r:") as archive:
        for member in archive:
            name = member.name
            parts = PurePosixPath(name).parts
            require(parts and str(PurePosixPath(name)) == name and
                    not PurePosixPath(name).is_absolute() and
                    all(re.fullmatch(r"[A-Za-z0-9_-][A-Za-z0-9_.-]*", part)
                        for part in parts) and
                    (name in ("manifest.json", "roles.sql") or
                     len(parts) > 1 and parts[0] in {"bin", "tools", "config", "web", "migrations", "lib", "share"}),
                    "Unsafe native archive path")
            limit = 384 * 1024**2 if name == "lib/chromium/chrome" else 256 * 1024**2
            require(member.isfile() and not member.pax_headers and
                    0 <= member.size <= limit and member.mode in (0o444, 0o555) and
                    name not in seen and len(seen) < 3000, "Unsafe native archive member")
            seen.add(name)
            total += member.size
            require(total <= ARCHIVE_LIMIT, "Oversized native archive payload")
            if name in (HELPER_NAME, "manifest.json"):
                require(0 < member.size <= HELPER_LIMIT and member.mode == 0o444,
                        "Missing or oversized native bootstrap input")
                content = archive.extractfile(member).read(HELPER_LIMIT + 1)
                require(len(content) == member.size, "Truncated native bootstrap input")
                if name == HELPER_NAME:
                    helper = content
                else:
                    manifest = public_json(content)
    require(helper is not None and isinstance(manifest, dict) and
            manifest.get("format") == "zakio-native-v1" and
            isinstance(manifest.get("files"), dict) and
            manifest["files"].get(HELPER_NAME) == hashlib.sha256(helper).hexdigest(),
            "Packaged native helper checksum differs")
    return helper


def run_helper(args, *, cwd, env):
    """Forward cancellation and wait for the updater's fail-stop cleanup.

    Never kill a still-running updater merely because a wrapper wait expired.
    A separate session avoids duplicate terminal signals; cancellation before
    Popen returns is remembered and delivered as soon as the child is available.
    """
    process = None
    cancelled = []
    pending = []
    previous = {}
    def forward(signum):
        if any(operation in args for operation in ("configure-host", "complete-install")) and signum == signal.SIGINT:
            # The foreground process group already receives terminal SIGINT.
            return
        try:
            process.send_signal(signum)
        except ProcessLookupError:
            pass
    def cancel(signum, frame):
        cancelled.append(signum)
        if process is None:
            pending.append(signum)
        else:
            forward(signum)
    try:
        for signum in (signal.SIGINT, signal.SIGTERM):
            previous[signum] = signal.signal(signum, cancel)
        # configure-host must retain the owner's controlling terminal for hidden
        # getpass input; all other operations retain isolated signal forwarding.
        process = subprocess.Popen(args, cwd=cwd, env=env, start_new_session=not any(operation in args for operation in ("configure-host", "complete-install")))
        # Only signals received before process assignment need forwarding here.
        # A signal arriving after assignment was already forwarded by cancel;
        # sending it twice can interrupt the child's cancellation cleanup.
        if pending:
            forward(pending[-1])
        returncode = process.wait()
        require(not cancelled, "Native delivery cancelled; child stopped; inspect target evidence")
        return subprocess.CompletedProcess(args, returncode)
    finally:
        for signum, handler in previous.items():
            signal.signal(signum, handler)


def stage(operation, archive, expected, profile, *, approved=False, approved_host_preparation=False, approved_host_configuration=False, failed_delivery_evidence=None):
    require(operation in ("install", "update", "prepare-host", "configure-host", "complete-install"), "Unsupported release operation")
    require(failed_delivery_evidence is None or operation == "complete-install", "Completion evidence is completion-only")
    require(operation != "complete-install" or failed_delivery_evidence is not None, "Completion needs the retained original delivery evidence")
    require(not approved_host_preparation or operation == "prepare-host", "Preparation approval is prepare-host only")
    require(not approved_host_configuration or operation == "configure-host", "Configuration approval is configure-host only")
    require(not approved or operation not in ("prepare-host", "configure-host"), "Delivery approval cannot authorize host setup")
    require(isinstance(expected, str) and re.fullmatch(r"[0-9a-f]{64}", expected),
            "An independently trusted native archive SHA256 is required")
    require(not (approved or approved_host_preparation or approved_host_configuration) or os.geteuid() == 0, "Approved native operation must run as root")
    with tempfile.TemporaryDirectory(prefix="zakio-release-", dir=staging_parent()) as temporary:
        directory = Path(temporary)
        info = directory.lstat()
        require(stat.S_ISDIR(info.st_mode) and info.st_uid == os.geteuid() and
                stat.S_IMODE(info.st_mode) == 0o700, "Unsafe exclusive release staging directory")
        copied = directory / "native.tar"
        snapshot(archive, copied, ARCHIVE_LIMIT, expected)
        content = helper_bytes(copied)
        copied_profile = directory / "host.json"
        snapshot(profile, copied_profile, PROFILE_LIMIT)
        public = public_json(copied_profile.read_bytes())
        require(isinstance(public, dict) and all(isinstance(value, str) for value in public.values()) and
                ((public.get("format") == "zakio-host-v1" and set(public) == PROFILE_FIELDS) or
                 (public.get("format") == "zakio-host-v2" and set(public) == PROXY_PROFILE_FIELDS)),
                "Invalid public host profile")
        helper = directory / "helper.py"
        with helper.open("xb") as output:
            output.write(content)
            output.flush()
            os.fsync(output.fileno())
            os.fchmod(output.fileno(), 0o400)
        args = ["/usr/bin/python3", "-I", str(helper), operation, "--package", str(copied),
                "--archive-sha256", expected, "--host-profile", str(copied_profile)]
        if approved:
            args.append("--approved-native-delivery")
        if approved_host_preparation:
            args.append("--approved-host-preparation")
        if approved_host_configuration:
            args.append("--approved-host-configuration")
        if failed_delivery_evidence is not None:
            args.extend(["--failed-delivery-evidence", str(failed_delivery_evidence)])
        # Fixed executable, argv (no shell), isolated imports and fixed PATH.
        # Delivery compares this profile to root-controlled host configuration.
        # Separately approved preparation instead requires a fresh target before
        # creating its authoritative public configuration.
        result = run_helper(args, cwd=directory,
                            env={"PATH": "/usr/sbin:/usr/bin:/sbin:/bin", "LANG": "C.UTF-8"})
        if result.returncode != 0: raise PackagedDeliveryStopped("Packaged native delivery stopped")


def main(argv=None):
    parser = argparse.ArgumentParser(description=__doc__)
    parser.error = lambda message: parser.exit(2, terminal_failure("Invalid release staging arguments; use only documented public options.") + "\n")
    parser.add_argument("operation", choices=("install", "update", "prepare-host", "configure-host", "complete-install"))
    parser.add_argument("--package", required=True, type=Path)
    parser.add_argument("--archive-sha256", required=True)
    parser.add_argument("--host-profile", required=True, type=Path)
    parser.add_argument("--approved-native-delivery", action="store_true")
    parser.add_argument("--approved-host-preparation", action="store_true")
    parser.add_argument("--approved-host-configuration", action="store_true")
    parser.add_argument("--failed-delivery-evidence", type=Path)
    args = parser.parse_args(argv)
    try:
        stage(args.operation, args.package, args.archive_sha256, args.host_profile,
              approved=args.approved_native_delivery,
              **({"failed_delivery_evidence": args.failed_delivery_evidence} if args.failed_delivery_evidence is not None else {}),
              **({"approved_host_configuration": True} if args.approved_host_configuration else {}),
              **({"approved_host_preparation": True} if args.approved_host_preparation else {}))
    except PackagedDeliveryStopped:
        raise SystemExit(1) from None
    except (Exception, KeyboardInterrupt):
        raise SystemExit(terminal_failure("Release staging stopped; verify the trusted archive, public profile and host prerequisites; no automatic retry or restore.")) from None


if __name__ == "__main__":
    main()
