#!/usr/bin/env python3
"""Движок установщика Zaryv OS.

Интерфейс запускает этот файл отдельным процессом
(`zaryv-setup-backend <команда>`) и читает stdout: одна JSON-строка — одно
событие. Договор: apps/installer/CONTRACT.md.

Команды: disks, hardware, install, demo-disks, demo-hardware, demo-install.
Пароли попадают только во временный файл creds (права 0600) и стираются
сразу после archinstall. В конфиг и в журнал они не пишутся.
"""

from __future__ import annotations

import json
import os
import re
import shutil
import subprocess
import sys
import tarfile
import tempfile
import threading
import time
import traceback
import urllib.request
import uuid
from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path

# Меньше 40 ГБ — диск не предлагаем. ГБ здесь десятичные, как на наклейке диска.
MIN_DISK_BYTES = 40 * 10**9
LOG_PATH = "/var/log/zaryv-setup.log"
TEMPLATE_PATH = Path("/usr/share/zaryv/archinstall.json")
APPLY_SCRIPT = Path("/usr/local/bin/zaryv-apply-installed")
HTTP_PORT = 8765
DEMO_SECONDS = 60.0

STAGE_TITLES = {
    "prepare": "Готовлю установку",
    "partition": "Размечаю диск",
    "encrypt": "Шифрую диск",
    "base": "Ставлю базовую систему",
    "packages": "Ставлю пакеты",
    "bootloader": "Ставлю загрузчик",
    "users": "Создаю пользователя",
    "branding": "Накладываю оформление Zaryv",
    "finish": "Завершаю установку",
}

# Те же файлы, что zaryv-install отдаёт в установленную систему.
BRANDING_PATHS = (
    "/usr/lib/os-release",
    "/etc/issue",
    "/etc/xdg/kcm-about-distrorc",
    "/etc/xdg/kdeglobals",
    "/etc/xdg/kwinrc",
    "/etc/xdg/autostart/zaryv-startup-sound.desktop",
    "/etc/xdg/autostart/zaryv-welcome-autostart.desktop",
    "/etc/modprobe.d/zaryv-nvidia.conf",
    "/etc/sddm.conf.d/zaryv-theme.conf",
    "/etc/plymouth/plymouthd.conf",
    "/etc/skel/.config/kdeglobals",
    "/etc/skel/.config/plasmarc",
    "/etc/skel/.config/kxkbrc",
    "/usr/share/pixmaps/zaryv.png",
    "/usr/share/pixmaps/zaryv.svg",
    "/usr/share/plasma/plasmoids/org.zaryv.startbutton",
    "/usr/share/plasma/look-and-feel/org.zaryv.desktop",
    "/usr/share/aurorae/themes/zaryv",
    "/usr/share/wallpapers/Zaryv",
    "/usr/share/wallpapers/ZaryvDawn",
    "/usr/share/color-schemes/ZaryvDawn.colors",
    "/usr/share/sddm/themes/zaryv",
    "/usr/share/plymouth/themes/zaryv",
    "/usr/share/sounds/zaryv",
    "/usr/share/grub/themes/zaryv",
    "/usr/share/calamares/branding",
    "/usr/local/bin/zaryv-startup-sound",
    "/usr/local/bin/zaryv-welcome-autostart",
    "/usr/bin/zaryv-welcome",
    "/usr/share/applications/zaryv-welcome.desktop",
    "/usr/local/bin/zaryv-chrome",
    "/usr/local/bin/zaryv-apply-look",
    "/usr/share/applications/zaryv-chrome.desktop",
    "/etc/xdg/autostart/zaryv-apply-look.desktop",
)

NVIDIA_PACKAGES = (
    "nvidia-open-dkms",
    "nvidia-utils",
    "lib32-nvidia-utils",
    "nvidia-settings",
)

PACMAN_INSTALL_RE = re.compile(
    r"\((\d+)\s*/\s*(\d+)\)\s+(?:installing|установка)\b",
    re.IGNORECASE,
)

# Фразы журнала archinstall → этап. Сначала более поздние, чтобы одна строка
# не откатывала прогресс назад.
STAGE_HINTS = (
    ("finish", ("installation complete", "installation completed", "successfully installed", "установка завершена")),
    ("branding", ("zaryv-apply-installed", "перенесены в установленную систему", "running custom command", "custom commands")),
    ("users", ("creating user", "adding user", "user creation", "создаю пользовател", "adding users")),
    ("bootloader", ("bootloader", "systemd-boot", "grub-install", "загрузчик")),
    ("packages", ("additional package", "installing packages", "дополнительн")),
    ("base", ("installing base", "base package", "pacstrap", "базов")),
    ("encrypt", ("luks", "cryptsetup", "encrypting", "шифрован")),
    ("partition", ("partition", "formatting", "wiping", "subvolume", "mkfs", "размеч", "форматир")),
    ("prepare", ("starting installation", "pre-install", "preparing installation")),
)

DISK_KEYS = (
    "path",
    "model",
    "size_bytes",
    "transport",
    "removable",
    "has_windows",
    "is_live_medium",
    "partitions",
    "selectable",
    "reason",
)


class InstallError(Exception):
    def __init__(self, stage: str, message: str):
        super().__init__(message)
        self.stage = stage
        self.message = message


class ProbeError(InstallError):
    def __init__(self, message: str):
        super().__init__("disks", message)


def emit(event: dict) -> None:
    try:
        sys.stdout.write(json.dumps(event, ensure_ascii=False) + "\n")
        sys.stdout.flush()
    except BrokenPipeError:
        raise SystemExit(0) from None


def is_root() -> bool:
    geteuid = getattr(os, "geteuid", None)
    if geteuid is None:
        return False
    return geteuid() == 0


def shell_quote(value: str) -> str:
    return "'" + value.replace("'", "'\"'\"'") + "'"


def stage_sequence(encrypt: bool) -> list[str]:
    stages = ["prepare", "partition"]
    if encrypt:
        stages.append("encrypt")
    stages.extend(["base", "packages", "bootloader", "users", "branding", "finish"])
    return stages


def stage_bands(encrypt: bool) -> dict[str, tuple[float, float]]:
    """Доля общего процента на этап. Пакеты занимают самую широкую полосу."""
    weights = {
        "prepare": 5,
        "partition": 10,
        "encrypt": 8,
        "base": 16,
        "packages": 40,
        "bootloader": 8,
        "users": 5,
        "branding": 6,
        "finish": 2,
    }
    order = stage_sequence(encrypt)
    total = sum(weights[item] for item in order)
    bands: dict[str, tuple[float, float]] = {}
    cursor = 0.0
    for stage_id in order:
        width = 100.0 * weights[stage_id] / total
        bands[stage_id] = (cursor, cursor + width)
        cursor += width
    start, _end = bands[order[-1]]
    bands[order[-1]] = (start, 100.0)
    return bands


def percent_for_packages(done: int, total: int, encrypt: bool) -> float:
    start, end = stage_bands(encrypt)["packages"]
    if total <= 0:
        return round(start, 1)
    value = start + (end - start) * (done / total)
    return round(value, 1)


def redact(line: str, secrets: list[str]) -> str:
    cleaned = line
    for secret in secrets:
        if secret:
            cleaned = cleaned.replace(secret, "***")
    return cleaned


def detect_stage(line: str) -> str | None:
    lowered = line.lower()
    for stage_id, hints in STAGE_HINTS:
        if any(hint in lowered for hint in hints):
            return stage_id
    return None


class ProgressParser:
    """Складывает строки archinstall в этапы и общий процент 0..100.

    Процент не уменьшается. Строки pacman `(N/M) installing` двигают полосу
    текущего этапа (база или пакеты).
    """

    def __init__(self, encrypt: bool, secrets: list[str] | None = None):
        self.encrypt = encrypt
        self.secrets = list(secrets or [])
        self.order = stage_sequence(encrypt)
        self.bands = stage_bands(encrypt)
        self.index = -1
        self.percent = 0.0
        self.detail = ""
        self.base_transaction_done = False

    def enter(self, stage_id: str) -> list[dict]:
        if stage_id not in self.order:
            return []
        target = self.order.index(stage_id)
        if target <= self.index:
            return []
        events: list[dict] = []
        while self.index < target:
            self.index += 1
            current = self.order[self.index]
            start, _end = self.bands[current]
            events.append({"type": "stage", "id": current, "title": STAGE_TITLES[current]})
            point = 100.0 if current == "finish" else start
            events.extend(self.set_percent(point, STAGE_TITLES[current]))
        return events

    def set_percent(self, value: float, detail: str) -> list[dict]:
        value = min(100.0, max(0.0, value))
        if value < self.percent:
            value = self.percent
        rounded = round(value, 1)
        if rounded < self.percent:
            rounded = self.percent
        changed = rounded > self.percent or detail != self.detail
        self.percent = max(self.percent, rounded)
        self.detail = detail
        if not changed:
            return []
        return [{"type": "progress", "percent": self.percent, "detail": detail}]

    def feed(self, line: str) -> list[dict]:
        clean = redact(line.rstrip("\r\n"), self.secrets)
        events: list[dict] = []
        stage_id = detect_stage(clean)
        if stage_id:
            events.extend(self.enter(stage_id))
        if clean.strip():
            events.append({"type": "log", "line": clean})
        match = PACMAN_INSTALL_RE.search(clean)
        if not match:
            return events
        done = int(match.group(1))
        total = int(match.group(2))
        if total <= 0:
            return events
        current = self.order[self.index] if self.index >= 0 else None
        if current == "base" and self.base_transaction_done:
            events.extend(self.enter("packages"))
            current = "packages"
        elif current not in {"base", "packages"}:
            events.extend(self.enter("packages"))
            current = "packages"
        if current == "base":
            detail = f"Ставлю базовую систему {done}/{total}"
            start, end = self.bands["base"]
            point = start + (end - start) * (done / total)
            if done >= total:
                self.base_transaction_done = True
        else:
            detail = f"Ставлю пакеты {done}/{total}"
            point = percent_for_packages(done, total, self.encrypt)
        events.extend(self.set_percent(point, detail))
        return events


def parse_archinstall_log(text: str, encrypt: bool = True, secrets: list[str] | None = None) -> list[dict]:
    parser = ProgressParser(encrypt, secrets)
    events: list[dict] = []
    for line in text.splitlines():
        events.extend(parser.feed(line))
    return events


def label_is_live(label: str | None) -> bool:
    if not label:
        return False
    return label.upper().startswith("ZARYV_")


def iter_block_nodes(node: dict):
    yield node
    for child in node.get("children") or []:
        if isinstance(child, dict):
            yield from iter_block_nodes(child)


def iter_partitions(disk: dict):
    for node in iter_block_nodes(disk):
        if node is disk:
            continue
        if node.get("type") == "part":
            yield node


def mountpoints_of(node: dict) -> list[str]:
    points: list[str] = []
    raw = node.get("mountpoints")
    if raw is None:
        raw = node.get("mountpoint")
    if isinstance(raw, list):
        points.extend(str(item) for item in raw if item)
    elif isinstance(raw, str) and raw:
        points.append(raw)
    return points


def as_int(value, default: int = 0) -> int:
    try:
        return int(value)
    except (TypeError, ValueError):
        return default


def as_bool_flag(value) -> bool:
    if isinstance(value, bool):
        return value
    return str(value).strip().lower() in {"1", "true", "yes"}


def child_named(parent: Path, name: str, want_dir: bool) -> Path | None:
    try:
        entries = list(parent.iterdir())
    except OSError:
        return None
    for entry in entries:
        if entry.name.lower() != name.lower():
            continue
        if want_dir and entry.is_dir():
            return entry
        if not want_dir and entry.is_file():
            return entry
    return None


def tree_has_windows(root: str | Path) -> bool:
    """Есть ли на смонтированном разделе Windows: EFI\\Microsoft, bootmgr или System32."""
    root_path = Path(root)
    if not root_path.is_dir():
        return False
    if child_named(root_path, "bootmgr", False) or child_named(root_path, "bootmgr.efi", False):
        return True
    efi = child_named(root_path, "EFI", True)
    if efi and child_named(efi, "Microsoft", True):
        return True
    boot = child_named(root_path, "Boot", True)
    if boot and child_named(boot, "bootmgr", False):
        return True
    windows = child_named(root_path, "Windows", True)
    if windows and child_named(windows, "System32", True):
        return True
    return False


def _mount_read_only(device: str, mountpoint: str) -> bool:
    attempts = (
        ["mount", "-o", "ro,noexec,nosuid,nodev", device, mountpoint],
        ["mount", "-t", "ntfs3", "-o", "ro", device, mountpoint],
        ["ntfs-3g", "-o", "ro", device, mountpoint],
    )
    for command in attempts:
        if shutil.which(command[0]) is None:
            continue
        result = subprocess.run(command, capture_output=True, text=True)
        if result.returncode == 0:
            return True
    return False


def _unmount(mountpoint: str) -> None:
    subprocess.run(["umount", mountpoint], capture_output=True, text=True)
    if os.path.ismount(mountpoint):
        subprocess.run(["umount", "-l", mountpoint], capture_output=True, text=True)


def partition_has_windows(part: dict) -> bool:
    fstype = str(part.get("fstype") or "").lower()
    if fstype in {"ext4", "btrfs", "xfs", "f2fs", "swap", "crypto_luks", "squashfs", "iso9660", "erofs"}:
        return False
    if fstype and fstype not in {"ntfs", "ntfs3", "vfat", "exfat", "fat32", "fat"}:
        return False
    if not fstype:
        return False
    for mounted in mountpoints_of(part):
        if tree_has_windows(mounted):
            return True
    device = str(part.get("path") or "")
    if not device.startswith("/dev/"):
        return False
    if not is_root():
        raise ProbeError(
            "Не удалось проверить, нет ли на диске Windows: "
            "нужны права root, чтобы смонтировать раздел только для чтения."
        )
    mountpoint = tempfile.mkdtemp(prefix="zaryv-ro-")
    mounted = False
    try:
        mounted = _mount_read_only(device, mountpoint)
        if not mounted:
            raise ProbeError(
                f"Не удалось смонтировать {device} только для чтения "
                "и проверить, стоит ли там Windows."
            )
        return tree_has_windows(mountpoint)
    finally:
        if mounted:
            _unmount(mountpoint)
        try:
            os.rmdir(mountpoint)
        except OSError:
            pass


def describe_disks(lsblk_data: dict, probe) -> list[dict]:
    devices = lsblk_data.get("blockdevices") or []
    described = []
    for disk in devices:
        if not isinstance(disk, dict) or disk.get("type") != "disk":
            continue
        name = str(disk.get("name") or "")
        if name.startswith(("loop", "zram", "ram", "fd", "sr")):
            continue
        path = str(disk.get("path") or (f"/dev/{name}" if name else ""))
        if not path:
            continue
        size_bytes = as_int(disk.get("size"))
        labels = [str(node.get("label") or "") for node in iter_block_nodes(disk)]
        live = any(label_is_live(label) for label in labels)
        partitions = list(iter_partitions(disk))
        has_windows = False
        if not live:
            for part in partitions:
                if probe(part):
                    has_windows = True
                    break
        reason = None
        if live:
            reason = "live_medium"
        elif has_windows:
            reason = "windows"
        elif size_bytes < MIN_DISK_BYTES:
            reason = "too_small"
        model = str(disk.get("model") or "").strip() or "Неизвестный диск"
        transport = str(disk.get("tran") or "").strip() or "unknown"
        described.append(
            {
                "path": path,
                "model": model,
                "size_bytes": size_bytes,
                "transport": transport,
                "removable": as_bool_flag(disk.get("rm")),
                "has_windows": has_windows,
                "is_live_medium": live,
                "partitions": len(partitions),
                "selectable": reason is None,
                "reason": reason,
            }
        )
    return described


def lsblk_json() -> dict:
    columns = "NAME,PATH,SIZE,TYPE,MODEL,TRAN,RM,FSTYPE,LABEL,MOUNTPOINTS"
    command = ["lsblk", "-J", "-b", "-o", columns]
    try:
        result = subprocess.run(command, capture_output=True, text=True)
    except FileNotFoundError as exc:
        raise InstallError("disks", "Не найдена команда lsblk.") from exc
    if result.returncode != 0:
        # Старый lsblk знает MOUNTPOINT, но не MOUNTPOINTS.
        fallback = ["lsblk", "-J", "-b", "-o", columns.replace("MOUNTPOINTS", "MOUNTPOINT")]
        result = subprocess.run(fallback, capture_output=True, text=True)
        if result.returncode != 0:
            raise InstallError("disks", "Не удалось получить список дисков.")
    try:
        data = json.loads(result.stdout or "{}")
    except json.JSONDecodeError as exc:
        raise InstallError("disks", "lsblk вернул не JSON, список дисков прочитать не вышло.") from exc
    if not isinstance(data, dict):
        raise InstallError("disks", "lsblk вернул неожиданный ответ.")
    return data


def cmd_disks() -> None:
    data = lsblk_json()
    disks = describe_disks(data, partition_has_windows)
    emit({"type": "disks", "disks": disks})


def _gpu_from_lspci() -> tuple[str, bool]:
    if shutil.which("lspci") is None:
        return "", False
    result = subprocess.run(["lspci"], capture_output=True, text=True)
    if result.returncode != 0:
        return "", False
    chosen = ""
    nvidia = False
    for line in result.stdout.splitlines():
        if not any(kind in line for kind in ("VGA", "3D", "Display")):
            continue
        name = line.split(": ", 1)[1].strip() if ": " in line else line.strip()
        if "nvidia" in line.lower() or "geforce" in line.lower():
            return name, True
        if not chosen:
            chosen = name
    return chosen, nvidia


def _gpu_from_sysfs() -> tuple[str, bool]:
    drm = Path("/sys/class/drm")
    if not drm.is_dir():
        return "", False
    for card in sorted(drm.glob("card[0-9]")):
        vendor_file = card / "device" / "vendor"
        try:
            vendor = vendor_file.read_text(encoding="utf-8").strip().lower()
        except OSError:
            continue
        if vendor in {"0x10de", "10de"}:
            return "NVIDIA", True
    return "", False


def detect_ram_bytes() -> int:
    meminfo = Path("/proc/meminfo")
    if not meminfo.is_file():
        raise InstallError("hardware", "Не удалось прочитать объём памяти (/proc/meminfo).")
    for line in meminfo.read_text(encoding="utf-8", errors="replace").splitlines():
        if line.startswith("MemTotal:"):
            return int(line.split()[1]) * 1024
    raise InstallError("hardware", "В /proc/meminfo нет строки MemTotal.")


def detect_vm() -> bool:
    cpuinfo = Path("/proc/cpuinfo")
    try:
        if "hypervisor" in cpuinfo.read_text(encoding="utf-8", errors="replace").lower():
            return True
    except OSError:
        pass
    detector = shutil.which("systemd-detect-virt")
    if not detector:
        return False
    result = subprocess.run([detector], capture_output=True, text=True)
    name = (result.stdout or "").strip().lower()
    return result.returncode == 0 and name not in {"", "none"}


def detect_hardware() -> dict:
    gpu, nvidia = _gpu_from_lspci()
    if not gpu:
        gpu, nvidia = _gpu_from_sysfs()
    return {
        "type": "hardware",
        "gpu": gpu or "Не определена",
        "nvidia": nvidia,
        "uefi": Path("/sys/firmware/efi").is_dir(),
        "ram_bytes": detect_ram_bytes(),
        "is_vm": detect_vm(),
    }


def cmd_hardware() -> None:
    emit(detect_hardware())


def demo_disks() -> dict:
    return {
        "type": "disks",
        "disks": [
            {
                "path": "/dev/nvme0n1",
                "model": "Samsung SSD 980 PRO 1TB",
                "size_bytes": 1000204886016,
                "transport": "nvme",
                "removable": False,
                "has_windows": True,
                "is_live_medium": False,
                "partitions": 3,
                "selectable": False,
                "reason": "windows",
            },
            {
                "path": "/dev/nvme1n1",
                "model": "KINGSTON SNVS500G",
                "size_bytes": 500107862016,
                "transport": "nvme",
                "removable": False,
                "has_windows": False,
                "is_live_medium": False,
                "partitions": 0,
                "selectable": True,
                "reason": None,
            },
            {
                "path": "/dev/sda",
                "model": "SanDisk Ultra",
                "size_bytes": 64023257088,
                "transport": "usb",
                "removable": True,
                "has_windows": False,
                "is_live_medium": True,
                "partitions": 2,
                "selectable": False,
                "reason": "live_medium",
            },
        ],
    }


def demo_hardware() -> dict:
    return {
        "type": "hardware",
        "gpu": "NVIDIA GeForce RTX 3090",
        "nvidia": True,
        "uefi": True,
        "ram_bytes": 34359738368,
        "is_vm": False,
    }


def cmd_demo_disks() -> None:
    emit(demo_disks())


def cmd_demo_hardware() -> None:
    emit(demo_hardware())


def read_request(required: bool) -> dict:
    """Один JSON-объект из stdin.

    Читаем, пока объект не соберётся целиком: интерфейс может не закрывать
    канал сразу после записи. Пустой stdin у demo-* — это нормально.
    """
    if sys.stdin is None or sys.stdin.isatty():
        if required:
            raise InstallError("prepare", "Нет данных установки: интерфейс должен передать JSON в stdin.")
        return {}
    decoder = json.JSONDecoder()
    chunks: list[str] = []
    while True:
        piece = sys.stdin.read(4096)
        if piece:
            chunks.append(piece)
        raw = "".join(chunks).lstrip()
        if raw:
            try:
                data, _end = decoder.raw_decode(raw)
            except json.JSONDecodeError:
                data = None
            else:
                if not isinstance(data, dict):
                    raise InstallError("prepare", "Запрос установки должен быть JSON-объектом.")
                return data
        if piece == "":
            break
    if not raw.strip():
        if required:
            raise InstallError("prepare", "Нет данных установки: интерфейс должен передать JSON в stdin.")
        return {}
    raise InstallError("prepare", "Не понял запрос установки: в stdin пришёл не JSON.")


def request_problems(data: dict) -> str | None:
    required = ("disk", "username", "password", "hostname", "locale", "keyboard", "timezone")
    missing = [key for key in required if not isinstance(data.get(key), str) or not str(data.get(key)).strip()]
    if missing:
        return "В запросе не хватает полей: " + ", ".join(missing) + "."
    username = data["username"]
    if not re.fullmatch(r"[a-z_][a-z0-9_-]{0,31}", username):
        return "Логин может содержать только строчные латинские буквы, цифры, _ и -."
    hostname = data["hostname"]
    if not re.fullmatch(r"[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?", hostname):
        return "Имя компьютера выглядит неправильно."
    disk = data["disk"]
    if ".." in disk or not re.fullmatch(r"/dev/[A-Za-z0-9][A-Za-z0-9_./-]*", disk):
        return "Непонятный путь к диску."
    password = data["password"]
    if "\n" in password or "\x00" in password:
        return "Пароль пользователя содержит недопустимые символы."
    if data.get("encrypt"):
        encrypt_password = data.get("encrypt_password")
        if not isinstance(encrypt_password, str) or encrypt_password == "":
            return "Включено шифрование диска, но пароль шифрования пустой."
        if "\n" in encrypt_password or "\x00" in encrypt_password:
            return "Пароль шифрования содержит недопустимые символы."
    return None


def is_nvidia_package(name: str) -> bool:
    return name.startswith("nvidia") or name.startswith("lib32-nvidia")


def _length(value: int, unit: str, sector: int) -> dict:
    return {
        "sector_size": {"unit": "B", "value": sector},
        "unit": unit,
        "value": value,
    }


def layout_disk(device: str, total_bytes: int, sector: int) -> tuple[dict, str]:
    """Целиком стереть диск: /boot FAT32 и Btrfs с подтомами @ @home @log @pkg."""
    total_mib = total_bytes // (1024 * 1024)
    boot_mib = 1024
    root_start = 1 + boot_mib
    root_mib = total_mib - root_start - 2
    if root_mib < 12288:
        raise InstallError(
            "partition",
            f"На {device} мало места. Для Zaryv OS нужно хотя бы 40 ГБ.",
        )
    root_id = str(uuid.uuid4())
    boot_id = str(uuid.uuid4())

    def part(fs_type, start_mib, size_mib, mountpoint, flags, btrfs, mount_options, obj_id):
        return {
            "btrfs": btrfs,
            "dev_path": None,
            "flags": flags,
            "fs_type": fs_type,
            "mount_options": mount_options,
            "mountpoint": mountpoint,
            "obj_id": obj_id,
            "size": _length(size_mib, "MiB", sector),
            "start": _length(start_mib, "MiB", sector),
            "status": "create",
            "type": "primary",
        }

    disk_config = {
        "config_type": "manual_partitioning",
        "btrfs_options": {"snapshot_config": None},
        "device_modifications": [
            {
                "device": device,
                "wipe": True,
                "partitions": [
                    part("fat32", 1, boot_mib, "/boot", ["boot"], [], [], boot_id),
                    part(
                        "btrfs",
                        root_start,
                        root_mib,
                        None,
                        [],
                        [
                            {"name": "@", "mountpoint": "/"},
                            {"name": "@home", "mountpoint": "/home"},
                            {"name": "@log", "mountpoint": "/var/log"},
                            {"name": "@pkg", "mountpoint": "/var/cache/pacman/pkg"},
                        ],
                        ["compress=zstd"],
                        root_id,
                    ),
                ],
            }
        ],
    }
    return disk_config, root_id


def build_install_files(template: dict, request: dict, nvidia: bool, total_bytes: int, sector: int) -> tuple[dict, dict]:
    problem = request_problems(request)
    if problem:
        raise InstallError("prepare", problem)
    config = json.loads(json.dumps(template))
    disk_config, root_id = layout_disk(request["disk"], total_bytes, sector)
    config["disk_config"] = disk_config
    config["hostname"] = request["hostname"]
    config["timezone"] = request["timezone"]
    config["kernels"] = ["linux-zen", "linux-lts"]
    config["silent"] = True
    locale = dict(config.get("locale_config") or {})
    locale["sys_lang"] = request["locale"]
    locale["sys_enc"] = locale.get("sys_enc") or "UTF-8"
    locale["kb_layout"] = request["keyboard"]
    config["locale_config"] = locale

    packages = [pkg for pkg in list(config.get("packages") or []) if isinstance(pkg, str)]
    if nvidia:
        for package in NVIDIA_PACKAGES:
            if package not in packages:
                packages.append(package)
    else:
        packages = [pkg for pkg in packages if not is_nvidia_package(pkg)]
    config["packages"] = packages

    commands = [item for item in list(config.get("custom_commands") or []) if isinstance(item, str)]
    full_name = request.get("full_name") or ""
    if isinstance(full_name, str) and full_name.strip():
        commands.append(
            f"chfn -f {shell_quote(full_name)} {shell_quote(request['username'])} || true"
        )
    if request.get("autologin"):
        user = request["username"]
        commands.append(
            "install -d /etc/sddm.conf.d && "
            "printf '%s\\n' '[Autologin]' "
            f"'User={user}' 'Session=plasma' "
            "> /etc/sddm.conf.d/zaryv-autologin.conf"
        )
    config["custom_commands"] = commands

    password = request["password"]
    creds = {
        "!users": [
            {
                "username": request["username"],
                "!password": password,
                "sudo": True,
                "groups": [],
            }
        ],
        "!root-password": password,
    }
    if request.get("encrypt"):
        config["disk_encryption"] = {
            "encryption_type": "luks",
            "partitions": [root_id],
            "hsm_device": None,
        }
        creds["encryption_password"] = request["encrypt_password"]
    else:
        config.pop("disk_encryption", None)

    leaked = secrets_in_config(config, secret_values(request))
    if leaked:
        raise InstallError(
            "prepare",
            "Внутренняя ошибка: пароль попал в открытый конфиг. Установка остановлена.",
        )
    return config, creds


def secret_values(request: dict) -> list[str]:
    values = []
    for key in ("password", "encrypt_password"):
        value = request.get(key)
        if isinstance(value, str) and value:
            values.append(value)
    return values


def secrets_in_config(config: dict, secrets: list[str]) -> bool:
    blob = json.dumps(config, ensure_ascii=False)
    return any(secret in blob for secret in secrets)


def disk_geometry(device: str) -> tuple[int, int]:
    name = device.rsplit("/", 1)[-1]
    size_path = Path(f"/sys/class/block/{name}/size")
    try:
        sectors = int(size_path.read_text(encoding="utf-8").strip())
    except (OSError, ValueError) as exc:
        raise InstallError("prepare", f"Не вижу диск {device}.") from exc
    sector = 512
    physical = Path(f"/sys/block/{name}/queue/physical_block_size")
    try:
        sector = int(physical.read_text(encoding="utf-8").strip()) or 512
    except (OSError, ValueError):
        sector = 512
    return sectors * 512, sector


def reason_message(reason: str | None, device: str) -> str:
    if reason == "windows":
        return f"На {device} стоит Windows. Этот диск стирать нельзя."
    if reason == "live_medium":
        return f"{device} — флешка с живой Zaryv OS. Выбери другой диск."
    if reason == "too_small":
        return f"На {device} меньше 40 ГБ. Для Zaryv OS этого мало."
    return f"Диск {device} нельзя выбрать для установки."


def busy_mounts(disk: dict) -> list[str]:
    points: list[str] = []
    for node in iter_block_nodes(disk):
        points.extend(mountpoints_of(node))
    return points


def write_secret_file(path: Path, payload: dict) -> None:
    data = json.dumps(payload, ensure_ascii=False, indent=4).encode("utf-8")
    flags = os.O_WRONLY | os.O_CREAT | os.O_TRUNC
    if hasattr(os, "O_NOFOLLOW"):
        flags |= os.O_NOFOLLOW
    fd = os.open(str(path), flags, 0o600)
    try:
        os.write(fd, data)
    finally:
        os.close(fd)
    try:
        os.chmod(path, 0o600)
    except OSError:
        pass


def shred_file(path: Path) -> None:
    try:
        size = path.stat().st_size
        with path.open("r+b") as handle:
            handle.write(b"\0" * size)
            handle.flush()
    except OSError:
        pass
    try:
        path.unlink()
    except OSError:
        pass


def append_log(line: str) -> None:
    try:
        with open(LOG_PATH, "a", encoding="utf-8") as handle:
            handle.write(line.rstrip("\n") + "\n")
    except OSError:
        return


def stage_branding_payload(payload_root: Path) -> None:
    def stage(source: str) -> None:
        src = Path(source)
        if not src.exists():
            return
        destination = payload_root / source.lstrip("/")
        destination.parent.mkdir(parents=True, exist_ok=True)
        if src.is_dir():
            shutil.copytree(src, destination, dirs_exist_ok=True)
        else:
            shutil.copy2(src, destination)

    for path in BRANDING_PATHS:
        stage(path)
    icons = Path("/usr/share/icons/hicolor")
    if icons.is_dir():
        for dirpath, _dirnames, filenames in os.walk(icons):
            for filename in filenames:
                if filename in {"zaryv.png", "zaryv.svg", "zaryv-launcher.svg"} or filename.startswith("zaryv-start"):
                    stage(str(Path(dirpath) / filename))


def start_branding_server(directory: Path) -> ThreadingHTTPServer:
    class Quiet(SimpleHTTPRequestHandler):
        def log_message(self, fmt: str, *args) -> None:
            print("http " + (fmt % args), file=sys.stderr)

    def quiet_handler(*args, **kwargs):
        return Quiet(*args, directory=str(directory), **kwargs)

    try:
        server = ThreadingHTTPServer(("127.0.0.1", HTTP_PORT), quiet_handler)
    except OSError as exc:
        raise InstallError(
            "prepare",
            f"Не поднялся локальный сервер с файлами оформления (порт {HTTP_PORT}).",
        ) from exc
    thread = threading.Thread(target=server.serve_forever, name="zaryv-branding-http", daemon=True)
    thread.start()
    deadline = time.time() + 5
    url = f"http://127.0.0.1:{HTTP_PORT}/zaryv-apply-installed"
    while time.time() < deadline:
        try:
            with urllib.request.urlopen(url, timeout=1) as response:
                response.read(1)
            return server
        except Exception:
            time.sleep(0.2)
    server.shutdown()
    server.server_close()
    raise InstallError("prepare", "Сервер с файлами оформления не ответил. Установка остановлена.")


def scrub_installed_creds() -> None:
    for path in (
        Path("/mnt/var/log/archinstall/user_credentials.json"),
        Path("/var/log/archinstall/user_credentials.json"),
    ):
        if path.exists():
            shred_file(path)


def run_archinstall(config_path: Path, creds_path: Path, parser: ProgressParser) -> int:
    command = ["archinstall", "--config", str(config_path), "--creds", str(creds_path), "--silent"]
    if shutil.which("stdbuf"):
        command = ["stdbuf", "-oL", "-eL", *command]
    if shutil.which("archinstall") is None and command[0] != "archinstall":
        # stdbuf стоит первым, сама команда — четвёртым аргументом.
        pass
    if shutil.which("archinstall") is None:
        raise InstallError("prepare", "В системе нет команды archinstall.")
    try:
        process = subprocess.Popen(
            command,
            stdout=subprocess.PIPE,
            stderr=subprocess.STDOUT,
            text=True,
            bufsize=1,
        )
    except FileNotFoundError as exc:
        raise InstallError("prepare", "Не удалось запустить archinstall.") from exc
    assert process.stdout is not None
    for line in process.stdout:
        append_log(redact(line.rstrip("\n"), parser.secrets))
        for event in parser.feed(line):
            if event.get("type") != "log":
                append_log(json.dumps(event, ensure_ascii=False))
            emit(event)
    return process.wait()


def cmd_install() -> None:
    request = read_request(required=True)
    problem = request_problems(request)
    if problem:
        raise InstallError("prepare", problem)
    if not is_root():
        raise InstallError("prepare", "Установку нужно запускать с правами администратора.")
    if not TEMPLATE_PATH.is_file():
        raise InstallError("prepare", f"Не найден профиль установки {TEMPLATE_PATH}.")
    if not APPLY_SCRIPT.is_file():
        raise InstallError("prepare", f"Не найден скрипт оформления {APPLY_SCRIPT}.")

    secrets = secret_values(request)
    parser = ProgressParser(bool(request.get("encrypt")), secrets)
    for event in parser.enter("prepare"):
        emit(event)

    try:
        template = json.loads(TEMPLATE_PATH.read_text(encoding="utf-8"))
    except (OSError, json.JSONDecodeError) as exc:
        raise InstallError("prepare", f"Не удалось прочитать профиль {TEMPLATE_PATH}.") from exc

    disks = describe_disks(lsblk_json(), partition_has_windows)
    chosen = next((disk for disk in disks if disk["path"] == request["disk"]), None)
    if chosen is None:
        raise InstallError("prepare", f"Диск {request['disk']} не найден.")
    if not chosen["selectable"]:
        raise InstallError("prepare", reason_message(chosen["reason"], request["disk"]))

    raw = lsblk_json()
    for disk in raw.get("blockdevices") or []:
        path = str(disk.get("path") or "")
        name = str(disk.get("name") or "")
        if path == request["disk"] or request["disk"] == f"/dev/{name}":
            mounts = busy_mounts(disk)
            if mounts:
                raise InstallError(
                    "prepare",
                    "Диск занят, разделы смонтированы (" + ", ".join(mounts) + "). "
                    "Размонтируй их и запусти установку снова.",
                )
            break

    total_bytes, sector = disk_geometry(request["disk"])
    if total_bytes < MIN_DISK_BYTES:
        raise InstallError("prepare", reason_message("too_small", request["disk"]))
    nvidia = bool(detect_hardware().get("nvidia"))
    config, creds = build_install_files(template, request, nvidia, total_bytes, sector)

    work = Path(tempfile.mkdtemp(prefix="zaryv-setup."))
    creds_path = work / "creds.json"
    config_path = work / "archinstall.json"
    server = None
    try:
        config_path.write_text(json.dumps(config, ensure_ascii=False, indent=4), encoding="utf-8")
        os.chmod(config_path, 0o644)
        write_secret_file(creds_path, creds)
        payload = work / "payload"
        http_dir = work / "http"
        payload.mkdir()
        http_dir.mkdir()
        stage_branding_payload(payload)
        with tarfile.open(http_dir / "payload.tar", "w") as archive:
            for item in payload.iterdir():
                archive.add(item, arcname=item.name)
        shutil.copy2(APPLY_SCRIPT, http_dir / "zaryv-apply-installed")
        server = start_branding_server(http_dir)
        for event in parser.set_percent(parser.bands["prepare"][1], "Запускаю archinstall"):
            emit(event)
        code = run_archinstall(config_path, creds_path, parser)
        shred_file(creds_path)
        if code != 0:
            current = parser.order[parser.index] if parser.index >= 0 else "prepare"
            title = STAGE_TITLES.get(current, current)
            raise InstallError(
                current,
                f"Установка остановилась на этапе «{title}». Подробности в журнале.",
            )
        for event in parser.enter("finish"):
            emit(event)
        scrub_installed_creds()
        emit({"type": "done", "reboot_recommended": True})
    finally:
        if server is not None:
            server.shutdown()
            server.server_close()
        if creds_path.exists():
            shred_file(creds_path)
        shutil.rmtree(work, ignore_errors=True)


def build_demo_events(request: dict) -> list[dict]:
    encrypt = bool(request.get("encrypt"))
    parser = ProgressParser(encrypt)
    script = [
        "Starting installation",
        "Wiping the selected disk",
        "Creating partitions",
        "Formatting /dev/nvme1n1p1 as fat32",
        "Creating btrfs subvolume @",
    ]
    if encrypt:
        script.append("Setting up LUKS encryption")
        script.append("cryptsetup luksFormat")
    script.extend(
        [
            "Installing base packages",
            "(1/40) installing filesystem",
            "(40/40) installing linux-lts",
            "Installing additional packages",
            "(1/1136) installing accountsservice",
            "(412/1136) installing python",
            "(1136/1136) installing steam",
            "Installing bootloader",
            "Installing systemd-boot",
            "Creating user zaryv",
            "Running custom commands",
            "Zaryv OS: брендинг, звуки и nvidia_drm.modeset=1 перенесены в установленную систему.",
            "Installation completed",
        ]
    )
    events: list[dict] = []
    for line in script:
        events.extend(parser.feed(line))
    events.append({"type": "done", "reboot_recommended": True})
    return events


def cmd_demo_install() -> None:
    """Те же события, что у install, но диск и пакеты не трогаем. Около 60 секунд."""
    request = read_request(required=False)
    events = build_demo_events(request)
    if not events:
        return
    pause = DEMO_SECONDS / max(1, len(events) - 1)
    for index, event in enumerate(events):
        if index:
            time.sleep(pause)
        emit(event)


COMMANDS = {
    "disks": cmd_disks,
    "hardware": cmd_hardware,
    "install": cmd_install,
    "demo-disks": cmd_demo_disks,
    "demo-hardware": cmd_demo_hardware,
    "demo-install": cmd_demo_install,
}


def main(argv: list[str]) -> None:
    try:
        sys.stdout.reconfigure(encoding="utf-8", line_buffering=True)
        sys.stderr.reconfigure(encoding="utf-8")
    except Exception:
        pass
    if len(argv) != 2 or argv[1] not in COMMANDS:
        names = ", ".join(COMMANDS)
        emit(
            {
                "type": "error",
                "stage": "prepare",
                "message": f"Неизвестная команда. Доступны: {names}.",
                "log_path": LOG_PATH,
            }
        )
        raise SystemExit(1)
    try:
        COMMANDS[argv[1]]()
    except InstallError as exc:
        append_log(exc.message)
        emit({"type": "error", "stage": exc.stage, "message": exc.message, "log_path": LOG_PATH})
        raise SystemExit(1) from None
    except Exception:
        print(traceback.format_exc(), file=sys.stderr)
        emit(
            {
                "type": "error",
                "stage": "prepare",
                "message": "Установщик столкнулся с непредвиденной ошибкой.",
                "log_path": LOG_PATH,
            }
        )
        raise SystemExit(1) from None


if __name__ == "__main__":
    main(sys.argv)
