#!/usr/bin/python3
"""Apply a verified SedPrint Linux GUI ZIP after the application exits."""

import argparse
import hashlib
import json
import os
from pathlib import Path, PurePosixPath
import shutil
import stat
import struct
import subprocess
import sys
import tempfile
import time
import uuid
import zipfile


MAX_FILES = 30000
MAX_UNCOMPRESSED = 2 * 1024 * 1024 * 1024
PROTECTED_DIRS = {"updates", "audit", "imprimante"}
PROTECTED_FILES = {"sedprint.config.ini", "logopreview.bmp", "crash.dmp"}


def arguments():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--package", required=True, type=Path)
    parser.add_argument("--target", required=True, type=Path)
    parser.add_argument("--app", required=True, type=Path)
    parser.add_argument("--pid", required=True, type=int)
    parser.add_argument("--result", required=True, type=Path)
    parser.add_argument("--data-root", required=True, type=Path)
    parser.add_argument("--from-version", required=True)
    parser.add_argument("--to-version", required=True)
    parser.add_argument("--expected-target", required=True)
    parser.add_argument("--sha256")
    parser.add_argument("--no-launch", action="store_true", help=argparse.SUPPRESS)
    return parser.parse_args()


def save_result(args, success, message):
    args.result.parent.mkdir(parents=True, exist_ok=True)
    payload = {
        "success": success,
        "message": message,
        "fromVersion": args.from_version,
        "toVersion": args.to_version,
    }
    temporary = args.result.with_name(args.result.name + ".new")
    temporary.write_text(json.dumps(payload, ensure_ascii=False), encoding="utf-8")
    os.replace(temporary, args.result)


def is_protected(relative):
    parts = [part.lower() for part in relative.parts]
    name = parts[-1]
    return (parts[0] in PROTECTED_DIRS or name in PROTECTED_FILES
            or name.endswith((".seq", ".log", ".dmp")))


def validated_entries(archive):
    entries = []
    seen = set()
    total_size = 0
    for info in archive.infolist():
        name = info.filename
        if (not name or name.startswith("/") or "\\" in name or ":" in name
                or "\x00" in name):
            raise ValueError("Arhiva conține o cale nesigură.")
        path = PurePosixPath(name)
        if any(part in ("", ".", "..") for part in name.rstrip("/").split("/")):
            raise ValueError("Arhiva conține o cale relativă nesigură.")
        if path in seen:
            raise ValueError("Arhiva conține căi duplicate.")
        seen.add(path)
        if is_protected(path):
            raise ValueError("Arhiva încearcă să înlocuiască datele utilizatorului.")
        mode = info.external_attr >> 16
        kind = stat.S_IFMT(mode)
        if kind not in (0, stat.S_IFREG, stat.S_IFDIR):
            raise ValueError("Arhiva conține legături sau fișiere speciale.")
        if info.is_dir() != (kind == stat.S_IFDIR) and kind != 0:
            raise ValueError("Tipul unei intrări din arhivă este inconsistent.")
        total_size += info.file_size
        entries.append((info, path))
        if len(entries) > MAX_FILES or total_size > MAX_UNCOMPRESSED:
            raise ValueError("Arhiva depășește limitele de siguranță.")
    if PurePosixPath("SedPrint") not in seen or PurePosixPath("SedPrintUpdater") not in seen:
        raise ValueError("Pachetul nu conține SedPrint și SedPrintUpdater la rădăcină.")
    if PurePosixPath("SedPrint.package.json") not in seen:
        raise ValueError("Pachetul nu conține identitatea versiunii Linux.")
    return entries


def check_elf(executable, target):
    header = executable.open("rb").read(20)
    machines = {"arm64": 183, "x86_64": 62}
    architecture = target.rsplit("-", 1)[-1]
    if (len(header) < 20 or header[:5] != b"\x7fELF\x02"
            or header[5] != 1 or struct.unpack("<H", header[18:20])[0] != machines.get(architecture)):
        raise ValueError("Executabilul nu este compatibil cu arhitectura acestui Linux.")


def extract_package(args, staging):
    with zipfile.ZipFile(args.package) as archive:
        entries = validated_entries(archive)
        metadata = json.loads(archive.read("SedPrint.package.json"))
        if metadata.get("product") != "SedPrint" or metadata.get("target") != args.expected_target:
            raise ValueError("Pachetul este destinat altei ediții sau distribuții Linux.")
        if args.to_version != "local" and metadata.get("version") != args.to_version:
            raise ValueError("Versiunea din pachet nu corespunde manifestului.")
        for info, relative in entries:
            destination = staging.joinpath(*relative.parts)
            if info.is_dir():
                destination.mkdir(parents=True, exist_ok=True)
                continue
            destination.parent.mkdir(parents=True, exist_ok=True)
            with archive.open(info) as source, destination.open("wb") as output:
                shutil.copyfileobj(source, output)
            mode = info.external_attr >> 16
            destination.chmod((mode & 0o777) or 0o644)
    for name in ("SedPrint", "SedPrintUpdater"):
        executable = staging / name
        if not executable.is_file():
            raise ValueError("Lipsește un executabil din pachet.")
        executable.chmod(executable.stat().st_mode | stat.S_IXUSR | stat.S_IXGRP)
    check_elf(staging / "SedPrint", args.expected_target)


def process_exited(pid):
    if pid <= 0:
        return True
    try:
        os.kill(pid, 0)
    except ProcessLookupError:
        return True
    except PermissionError:
        pass
    return False


def wait_for_exit(pid):
    for _ in range(300):
        if process_exited(pid):
            return
        time.sleep(0.1)
    raise TimeoutError("SedPrint nu s-a închis; actualizarea a fost anulată.")


def safe_destination(target, relative):
    current = target
    for part in relative.parts[:-1]:
        current = current / part
        if current.is_symlink():
            raise ValueError("Destinația conține o legătură simbolică nesigură.")
    return current / relative.parts[-1]


def replace_files(staging, target, backup):
    files = sorted(path for path in staging.rglob("*") if path.is_file())
    touched = []
    try:
        for source in files:
            relative = source.relative_to(staging)
            destination = safe_destination(target, relative)
            destination.parent.mkdir(parents=True, exist_ok=True)
            existed = destination.exists() or destination.is_symlink()
            if existed:
                saved = backup / relative
                saved.parent.mkdir(parents=True, exist_ok=True)
                if destination.is_symlink():
                    os.symlink(os.readlink(destination), saved)
                else:
                    shutil.copy2(destination, saved)
            temporary = destination.with_name(destination.name + ".update-new")
            shutil.copy2(source, temporary)
            os.replace(temporary, destination)
            touched.append((relative, existed))
    except Exception:
        for relative, existed in reversed(touched):
            destination = target / relative
            if existed:
                os.replace(backup / relative, destination)
            else:
                destination.unlink(missing_ok=True)
        raise


def launch(args):
    if args.no_launch:
        return
    subprocess.Popen([str(args.app), "--show", "--updated-from", args.from_version],
                     cwd=args.target, start_new_session=True,
                     stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL,
                     stderr=subprocess.DEVNULL)


def main():
    args = arguments()
    staging = None
    try:
        target = args.target.absolute()
        data_root = args.data_root.absolute()
        if (not target.is_dir() or target.is_symlink()
                or args.app.absolute() != target / "SedPrint"
                or not args.app.is_file() or args.app.is_symlink()
                or not data_root.is_dir() or data_root.is_symlink()
                or args.result.absolute() != data_root / "updates" / "last-update-result.json"
                or not args.package.is_file() or args.package.is_symlink()
                or not os.access(target, os.W_OK)):
            raise ValueError("Căile sau permisiunile actualizării Linux sunt invalide.")
        if args.sha256:
            digest = hashlib.sha256()
            with args.package.open("rb") as package:
                for block in iter(lambda: package.read(1024 * 1024), b""):
                    digest.update(block)
            if digest.hexdigest() != args.sha256.lower():
                raise ValueError("SHA-256 al pachetului nu corespunde manifestului.")
        staging_root = data_root / "updates" / "staging"
        staging_root.mkdir(parents=True, exist_ok=True)
        staging = Path(tempfile.mkdtemp(prefix="linux-", dir=staging_root))
        extract_package(args, staging)
        wait_for_exit(args.pid)
        backup = data_root / "updates" / "backups" / (
            args.from_version + "-" + time.strftime("%Y%m%d-%H%M%S") + "-" + uuid.uuid4().hex[:8])
        replace_files(staging, target, backup)
        save_result(args, True, f"Actualizarea la versiunea {args.to_version} a fost aplicată. Copia precedentă este în {backup}.")
        try:
            launch(args)
        except OSError:
            save_result(args, True,
                        f"Actualizarea la versiunea {args.to_version} a fost aplicată, dar SedPrint nu a repornit. Deschide aplicația manual.")
        return 0
    except (OSError, ValueError, TimeoutError, zipfile.BadZipFile, json.JSONDecodeError) as error:
        message = str(error) or "Actualizarea Linux a eșuat."
        try:
            save_result(args, False, message)
        except OSError:
            pass
        print(message, file=sys.stderr)
        try:
            wait_for_exit(args.pid)
            launch(args)
        except (OSError, TimeoutError):
            pass
        return 1
    finally:
        if staging is not None:
            shutil.rmtree(staging, ignore_errors=True)


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