#!/usr/bin/python3 -I
"""Privileged package setup. Only named, fixed operations can be requested."""
import configparser
import fcntl
import gzip
import hashlib
import io
import json
import os
from pathlib import Path
import platform
import shutil
import subprocess
import sys
import tempfile

sys.path.insert(0, str(Path(__file__).resolve().parent))
from compatibility import feature_status
from app_progress import PRODUCTS, apt_status_options, emit_event, plan

CACHE = Path("/var/cache/compact-apps")
WAY = Path("/var/lib/waydroid")
GOOGLE_SIGNER = "EB4C1BFD4F042F6DDDCCEC917721F63BD38B4796"
APT = ["apt-get", "-o", "Acquire::Retries=3", "-o", "DPkg::Lock::Timeout=90",
       "-o", "APT::Update::Error-Mode=any", "-o", "Dpkg::Use-Pty=0"]
OTA = "https://ota.waydro.id"
# Zoom Workplace 7.2.5.6661, verified against the Zoom builder signature
# (84C365D6CC9A4886CA926BCC4F2197399706AC24) and actual Debian archive members.
ZOOM_VERSION = "7.2.5.6661"
ZOOM_SHA256 = "5cd7b9f1e6dc7226a44193df23d0664790496e8267f26152b0cbbd5888025444"
ESSENTIALS_READY = Path("/var/lib/compact-apps/essentials-v2")

def run(*args, **kwargs):
    return subprocess.run(list(map(str, args)), check=True, **kwargs)

def output(*args):
    return run(*args, stdout=subprocess.PIPE, text=True).stdout.strip()

def emit(message):
    print(message, flush=True)

def digest(path):
    with path.open("rb") as handle:
        return hashlib.file_digest(handle, "sha256").hexdigest()

def installed(package):
    state = subprocess.run(["dpkg-query", "-W", "-f=${Status}", package], text=True,
                           capture_output=True, check=False)
    return state.returncode == 0 and state.stdout == "install ok installed"

def install_chrome():
    if feature_status()[0] != "ready":
        raise RuntimeError("Google Chrome requires a verified 64-bit x86 CPU with SSE3 (pni). "
                           "Use a compatible CPU, or check the virtual machine CPU settings.")
    if installed("google-chrome-stable"):
        return
    # Use a scoped bootstrap source for the first verified download. Chrome installs
    # and maintains its own signed repo when dpkg configures the package.
    area = CACHE / "chrome"
    area.mkdir(parents=True, exist_ok=True)
    key = area / "signing.gpg"
    with tempfile.TemporaryDirectory(dir=area) as tmp:
        pub = Path(tmp) / "google.pub"
        run("curl", "--fail", "--location", "--proto", "=https", "--proto-redir", "=https",
            "--connect-timeout", "15", "--max-time", "120", "--retry", "3", "--output", pub,
            "https://dl.google.com/linux/linux_signing_key.pub")
        gpg = ["gpg", "--homedir", tmp, "--batch"]
        keyring = Path(tmp) / "downloaded.gpg"
        run(*gpg, "--dearmor", "--output", keyring, pub)
        data = run(*gpg, "--no-autostart", "--no-default-keyring", "--keyring", keyring,
                   "--export", GOOGLE_SIGNER, stdout=subprocess.PIPE).stdout
        if not data:
            raise RuntimeError("Google's documented active signing key was not found.")
        key.write_bytes(data)
        key.chmod(0o644)
    install_from_signed_repo("google-chrome-stable", area, key, "https://dl.google.com/linux/chrome/deb/")

def install_from_signed_repo(package_name, area, key, url):
    lists = area / "lists"
    lists.mkdir(parents=True, exist_ok=True)
    source = area / "publisher.list"
    source.write_text(f"deb [arch=amd64 signed-by={key}] {url} stable main\n")
    scope = ["-o", f"Dir::Etc::sourcelist={source}", "-o", "Dir::Etc::sourceparts=-",
             "-o", f"Dir::State::lists={lists}", "-o", "Dir::Cache::pkgcache=",
             "-o", "Dir::Cache::srcpkgcache="]
    run(*APT, *scope, "update")
    metadata = output("apt-cache", *scope, "show", "--no-all-versions", package_name)
    fields = dict(line.split(": ", 1) for line in metadata.splitlines() if ": " in line and not line[0].isspace())
    checksum = fields["SHA256"]
    if len(checksum) != 64 or any(c not in "0123456789abcdef" for c in checksum):
        raise RuntimeError("Missing SHA-256 in signed APT package index.")
    cached = next((p for p in area.glob("*.deb") if digest(p) == checksum), None)
    product = "Google Chrome" if package_name == "google-chrome-stable" else "ChatGPT"
    if cached is None:
        leaf = Path(fields.get("Filename", "")).name
        expected_file = area / leaf if leaf else None
        watch = str(expected_file) if expected_file and not expected_file.exists() else ""
        size = fields.get("Size", "")
        emit_event("transfer", product, size=int(size) if size.isdecimal() else 0, path=watch)
        run(*APT, *apt_status_options(), *scope, "download", package_name+"="+fields["Version"], cwd=area)
        cached = next((p for p in area.glob("*.deb") if digest(p) == checksum), None)
    if cached is None:
        raise RuntimeError(f"Downloaded {package_name} package does not match the signed index.")
    emit_event("verified", product)
    run(*APT, "update")
    run(*APT, *apt_status_options(), "-y", "install", cached)
    if not installed(package_name):
        raise RuntimeError(f"{package_name} package configuration is incomplete.")
    shutil.rmtree(area)

def install_chatgpt():
    if installed("chatgpt"):
        return
    install_from_signed_repo("chatgpt", CACHE / "chatgpt",
                             Path("/usr/share/keyrings/newworld-openai-bootstrap.gpg"),
                             "https://persistent.oaistatic.com/codex-app-prod/linux/deb")

def install_zoom():
    if installed("zoom"):
        version = output("dpkg-query", "-W", "-f=${Version}", "zoom")
        if subprocess.run(["dpkg","--compare-versions",version,"ge",ZOOM_VERSION]).returncode == 0:
            return
    package = CACHE / "zoom_amd64.deb"
    if not package.is_file() or digest(package) != ZOOM_SHA256:
        package.unlink(missing_ok=True)
        # Keep partial bytes for retry. The whole file must match the pinned
        # digest before handing it to dpkg, including after a resumed transfer.
        staging = CACHE / "zoom_amd64.partial"
        emit_event("transfer", "Zoom Workplace", size=304618854, path=str(staging))
        url = f"https://zoom.us/client/{ZOOM_VERSION}/zoom_amd64.deb"
        curl = ["curl", "--fail", "--location", "--proto", "=https", "--proto-redir", "=https",
                "--retry", "3", "--connect-timeout", "15", "--max-time", "1800", "--output", staging]
        if not staging.is_file() or digest(staging) != ZOOM_SHA256:
            try:
                run(*curl, "--continue-at", "-", url)
            except subprocess.CalledProcessError as error:
                if error.returncode not in (33, 36):
                    raise
                staging.unlink(missing_ok=True)
                run(*curl, url)
        if digest(staging) != ZOOM_SHA256:
            staging.unlink(missing_ok=True)
            raise RuntimeError("Zoom package SHA-256 does not match the verified release.")
        staging.replace(package)
    emit_event("verified", "Zoom Workplace")
    run(*APT, "update")
    run(*APT, *apt_status_options(), "-y", "--no-install-recommends", "install", package)
    if not installed("zoom"):
        raise RuntimeError("Zoom Workplace package configuration is incomplete.")
    package.unlink(missing_ok=True)

def install_suite():
    run("/usr/local/lib/compact-artcraft/install-all")

def install_essentials():
    tasks = []
    if feature_status()[0] == "ready":
        tasks.append(("Google Chrome", install_chrome))
    else:
        emit("Skipping Google Chrome because this machine lacks verified 64-bit x86 SSE3 support.")
    tasks.extend([("Zoom Workplace", install_zoom), ("ChatGPT", install_chatgpt), ("ArtCraft", install_suite)])
    failures = []
    for product, operation in tasks:
        try:
            emit(product)
            emit_event("start",product)
            operation()
            emit_event("done",product)
        except (OSError, ValueError, KeyError, RuntimeError, subprocess.CalledProcessError) as error:
            emit_event("failed",product)
            emit(f"{product}: {error}")
            failures.append(product)
    if failures:
        raise RuntimeError("Retry setup to complete: " + ", ".join(failures))
    ESSENTIALS_READY.parent.mkdir(mode=0o755, exist_ok=True)
    ESSENTIALS_READY.touch(mode=0o644)

def waydroid_ready():
    cfg = WAY / "waydroid.cfg"
    if not (cfg.is_file() and (WAY / "rootfs").is_dir() and (WAY / "lxc/waydroid/config").is_file()):
        return False
    config = configparser.ConfigParser(interpolation=None)
    try:
        config.read(cfg)
        images = Path(config.get("waydroid", "images_path", fallback=str(WAY / "images")))
    except configparser.Error:
        return False
    return all((images / name).is_file() and (images / name).stat().st_size > 0
               for name in ("system.img", "vendor.img"))

def kernel_binder():
    if Path("/sys/module/binder_linux").exists() or Path("/dev/binderfs/binder-control").exists():
        return True
    config = Path("/boot") / ("config-" + platform.release())
    text = ""
    if config.is_file():
        text = config.read_text()
    elif Path("/proc/config.gz").is_file():
        with gzip.open("/proc/config.gz","rt") as kernel:
            text = kernel.read()
    return any(f"CONFIG_ANDROID_BINDER_IPC{suffix}={mode}" in text.splitlines()
               for suffix in ("", "_RUST") for mode in ("y","m"))

def needs_software_graphics():
    nodes = list(Path("/sys/class/drm").glob("renderD*"))
    return not nodes or all((p / "device/driver").resolve().name == "nvidia" for p in nodes)

def seed_android_locale(config_path, locale, software_render=False):
    # Android reads ro.product.locale only in the absence of a user-selected
    # locale. Set that default once, before the first Android session.
    config = configparser.ConfigParser(interpolation=None)
    config.optionxform = str
    with config_path.open() as current:
        config.read_file(current)
    if not config.has_section("properties"):
        config.add_section("properties")
    config["properties"].setdefault("ro.product.locale", locale)
    config["properties"].setdefault("persist.waydroid.multi_windows", "true")
    if software_render:
        config["properties"].setdefault("ro.hardware.gralloc", "default")
        config["properties"].setdefault("ro.hardware.egl", "swiftshader")
    save_config(config_path, config)

def write_atomic(path, data):
    mode = path.stat().st_mode & 0o777 if path.exists() else 0o644
    with tempfile.NamedTemporaryFile("wb", dir=path.parent, delete=False) as temp:
        try:
            temp.write(data)
            temp.flush()
            os.fsync(temp.fileno())
            os.chmod(temp.name, mode)
            os.replace(temp.name, path)
        finally:
            Path(temp.name).unlink(missing_ok=True)

def save_config(path, config):
    source = io.StringIO()
    config.write(source)
    write_atomic(path, source.getvalue().encode())

RENDER_PROPERTIES = {"ro.hardware.egl": "swiftshader", "ro.hardware.gralloc": "default"}
GRAPHICS_BASELINE = Path("/var/lib/compact-apps/graphics-original.json")

def change_graphics(software):
    if not waydroid_ready():
        raise RuntimeError("Finish Android setup first.")
    path = WAY / "waydroid.cfg"
    original = path.read_bytes()
    config = configparser.ConfigParser(interpolation=None)
    config.optionxform = str
    config.read_string(original.decode())
    if not config.has_section("properties"):
        config.add_section("properties")
    props = config["properties"]
    previous = {key: props.get(key) for key in RENDER_PROPERTIES}
    has_baseline = GRAPHICS_BASELINE.exists()
    if software:
        if previous != RENDER_PROPERTIES and not has_baseline:
            GRAPHICS_BASELINE.parent.mkdir(parents=True, exist_ok=True)
            write_atomic(GRAPHICS_BASELINE, json.dumps(previous).encode())
        props.update(RENDER_PROPERTIES)
    elif has_baseline:
        baseline = json.loads(GRAPHICS_BASELINE.read_text())
        for key in RENDER_PROPERTIES:
            if baseline.get(key) is None:
                props.pop(key, None)
            else:
                props[key] = baseline[key]
    elif previous == RENDER_PROPERTIES:
        # Earlier installers automatically chose the software pair on GPUs
        # without a Mesa render node. Restore upstream detection in that case.
        for key in RENDER_PROPERTIES:
            props.pop(key, None)
    try:
        save_config(path, config)
        # Waydroid regenerates the runtime offline and restarts an active session.
        run("waydroid", "--details-to-stdout", "upgrade", "-o")
    except (OSError, subprocess.SubprocessError):
        write_atomic(path, original)
        if software and not has_baseline:
            GRAPHICS_BASELINE.unlink(missing_ok=True)
        try:
            run("waydroid", "--details-to-stdout", "upgrade", "-o")
        except (OSError, subprocess.SubprocessError) as rollback_error:
            raise RuntimeError("Restored the original configuration on disk. Restart Android and retry.") from rollback_error
        raise
    if not software:
        GRAPHICS_BASELINE.unlink(missing_ok=True)

def prepare_android(locale):
    if not kernel_binder():
        raise RuntimeError("This kernel lacks Android Binder support. Boot a supported kernel and retry.")
    if not Path("/sys/module/binder_linux").exists():
        run("modprobe", "binder_linux")
        run("udevadm", "settle", "--timeout=20")
    has_binderfs = any(row.split()[-1:] == ["binder"] for row in Path("/proc/filesystems").read_text().splitlines())
    if not has_binderfs and not all(any((Path("/dev")/(prefix+name)).exists()
                                        for prefix in ("","anbox-")) for name in ("binder","hwbinder","vndbinder")):
        raise RuntimeError("Static Binder nodes are missing. Restart the installed OS and retry.")
    if not installed("waydroid") or not installed("aapt"):
        # Package lists on an offline installation may initially be empty.
        run(*APT, "update")
        policy = output("apt-cache", "policy", "waydroid")
        if "Candidate:" not in policy or "Candidate: (none)" in policy:
            source = Path("/etc/apt/sources.list.d/compact-waydroid-backports.sources")
            source.write_text("Types: deb\nURIs: https://deb.debian.org/debian\nSuites: trixie-backports\n"
                              "Components: main\nSigned-By: /usr/share/keyrings/debian-archive-keyring.gpg\n")
            run(*APT, "update")
        run(*APT, "-y", "install", "waydroid/trixie-backports", "aapt")
    if not waydroid_ready():
        run("waydroid", "--details-to-stdout", "init", "-c", OTA+"/system", "-v", OTA+"/vendor", "-s", "VANILLA")
        if not waydroid_ready():
            raise RuntimeError("Waydroid initialization is incomplete. Check the download and retry.")
    marker = Path("/var/lib/compact-apps/android-ready")
    if not marker.exists():
        software = needs_software_graphics()
        if software:
            emit("Using software rendering for the available graphics hardware.")
        seed_android_locale(WAY / "waydroid.cfg", locale, software_render=software)
        run("waydroid", "--details-to-stdout", "upgrade", "-o")
        if not waydroid_ready():
            raise RuntimeError("Waydroid image configuration did not complete.")
    run("systemctl", "enable", "--now", "waydroid-container.service")
    marker.parent.mkdir(mode=0o755, exist_ok=True)
    marker.touch(mode=0o644)

def update_android():
    if not waydroid_ready():
        raise RuntimeError("Finish Android setup before updating its system image.")
    run("waydroid", "--details-to-stdout", "upgrade")
    if not waydroid_ready():
        raise RuntimeError("Android image update did not complete.")

def is_live():
    return ("boot=live" in Path("/proc/cmdline").read_text().split()
            or Path("/run/live/medium").is_mount())

def main():
    actions = {"essentials": install_essentials, "zoom": install_zoom, "chatgpt": install_chatgpt, "chrome": install_chrome, "android-he": lambda: prepare_android("he-IL"),
               "android-en": lambda: prepare_android("en-US"), "android-update": update_android,
               "graphics-hardware": lambda: change_graphics(False),
               "graphics-software": lambda: change_graphics(True)}
    if os.geteuid() != 0 or len(sys.argv) != 2 or sys.argv[1] not in actions:
        return 2
    if is_live():
        raise RuntimeError("Install to disk before setting up Chrome or Android.")
    os.environ.update(PATH="/usr/sbin:/usr/bin:/sbin:/bin", HOME="/root", LC_ALL="C",
                      DEBIAN_FRONTEND="noninteractive", PYTHONUNBUFFERED="1")
    if output("dpkg", "--print-architecture") != "amd64":
        raise RuntimeError("This edition requires an amd64 installation.")
    os.umask(0o022)
    CACHE.mkdir(mode=0o755, exist_ok=True)
    with (CACHE / "setup.lock").open("a") as lock:
        try:
            fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
        except BlockingIOError:
            raise RuntimeError("Another setup is running. Wait for it to finish.") from None
        operation = sys.argv[1]
        tracked = operation == "essentials" or operation in PRODUCTS
        if tracked:
            os.environ["NEWWORLD_APP_PROGRESS"] = "1"
            emit_event("plan", weights=plan(operation, feature_status()[0] == "ready"))
            if operation in PRODUCTS: emit_event("start", PRODUCTS[operation])
        emit("Starting " + operation)
        actions[operation]()
        if operation in PRODUCTS: emit_event("done", PRODUCTS[operation])
        emit("Setup complete.")
    return 0

if __name__ == "__main__":
    try:
        sys.exit(main())
    except (OSError, ValueError, KeyError, RuntimeError, subprocess.CalledProcessError) as error:
        print(error, file=sys.stderr, flush=True)
        sys.exit(1)
