#!/usr/bin/python3
"""Supported APT administration. Availability checks never install packages."""
import argparse
import csv
import fcntl
import json
import os
from pathlib import Path
import re
import shlex
import subprocess
import sys
import tempfile
import time

STATE_DIR = Path(os.environ.get("HARRESI_APT_STATE_DIR", "/var/lib/harresi"))
CONFIG = Path(os.environ.get("HARRESI_APT_CONFIG", "/etc/harresi/update.conf"))
MANIFEST = Path(os.environ.get("HARRESI_PACKAGE_MANIFEST", "/usr/share/harresi/updater/packages.tsv"))
SERVICES = ("suricata_ids", "suricata_idps", "suricata_mitm", "sslproxyd", "suricata-aggregator", "suricata-monitor")
DEFAULT_PACKAGES = tuple("harresi-" + p for p in (
    "repo-client", "base", "ssh", "users", "menu", "network", "firewall", "sslproxy",
    "suricata", "audit", "logs", "aide", "time-sync", "hardening", "updater",
    "suricata-rules-repo", "client", "server"))


def command(*args, check=True, timeout=1800):
    result = subprocess.run(args, text=True, stdout=subprocess.PIPE,
                            stderr=subprocess.PIPE, timeout=timeout,
                            env=dict(os.environ, LC_ALL="C"))
    if check and result.returncode:
        raise RuntimeError(f"{' '.join(args)}: {result.stderr.strip() or result.stdout.strip() or result.returncode}")
    return result


def atomic(path, data, mode=0o644):
    path.parent.mkdir(parents=True, exist_ok=True)
    fd, name = tempfile.mkstemp(prefix="." + path.name + ".", dir=path.parent)
    try:
        with os.fdopen(fd, "w") as stream:
            stream.write(data)
            stream.flush()
            os.fsync(stream.fileno())
        os.chmod(name, mode)
        os.replace(name, path)
    finally:
        if os.path.exists(name):
            os.unlink(name)


def settings(path):
    values = {}
    if path.is_file():
        for line in path.read_text().splitlines():
            match = re.fullmatch(r"([A-Z_]+)=(.*)", line.strip())
            if match:
                try:
                    tokens = shlex.split(match[2])
                    values[match[1]] = tokens[0] if len(tokens) == 1 else ""
                except ValueError:
                    pass
    return values


def packages():
    if not MANIFEST.is_file():
        return DEFAULT_PACKAGES
    with MANIFEST.open() as stream:
        return tuple(row[0] for row in csv.reader(stream, delimiter="\t")
                     if row and re.fullmatch(r"harresi-[a-z0-9][a-z0-9+.-]*", row[0]))


def installed(package):
    result = command("dpkg-query", "-W", "-f=${Status}\t${Version}", package, check=False)
    if result.returncode or not result.stdout.startswith("install ok installed\t"):
        return "not-installed"
    return result.stdout.partition("\t")[2].strip()


def candidate(package):
    result = command("apt-cache", "policy", package)
    match = re.search(r"^\s*Candidate:\s*(\S+)", result.stdout, re.M)
    if not match:
        raise RuntimeError(f"APT no devolvió información de la versión candidata: {package}")
    return match[1]


def versions(package):
    validate_package(package)
    result = command("apt-cache", "madison", package)
    return list(dict.fromkeys(line.split("|")[1].strip() for line in result.stdout.splitlines()
                             if "|" in line and len(line.split("|")) >= 2))


def validate_package(package):
    if package not in packages():
        raise ValueError("Paquete no permitido por el manifiesto Harresi.")


def save_state(values):
    atomic(STATE_DIR / "update.state", "".join(f"{k}={shlex.quote(str(v))}\n" for k, v in values.items()))


def check_updates(automatic=False):
    config = settings(CONFIG)
    if automatic and config.get("AUTO_CHECK_ENABLED", "yes") != "yes":
        print("Comprobación automática desactivada; el informe anterior no se modifica.")
        return
    previous = settings(STATE_DIR / "update.state")
    now = int(time.time())
    state = dict(previous, LAST_CHECK=now, CHECK_STATUS="unavailable", UPDATE_AVAILABLE="unknown",
                 METADATA_STATUS="stale", PACKAGE_REPORT=str(STATE_DIR / "update-packages.tsv"))
    try:
        refresh = config.get("APT_UPDATE_BEFORE_CHECK", "yes") == "yes"
        if refresh:
            command("apt-get", "-o", "APT::Update::Error-Mode=any", "update")
            state["LAST_METADATA_REFRESH"] = now
            state["METADATA_STATUS"] = "fresh"
        rows = []
        for package in packages():
            current = installed(package)
            latest = candidate(package)
            if latest == "(none)":
                available = "unavailable"
            elif current == "not-installed":
                available = "no"
            else:
                newer = command("dpkg", "--compare-versions", latest, "gt", current, check=False)
                if newer.returncode not in (0, 1):
                    raise RuntimeError(f"No se pudieron comparar las versiones de {package}.")
                available = "yes" if newer.returncode == 0 else "no"
            rows.append((package, current, latest, available))
        outdated = sum(row[3] == "yes" for row in rows)
        unavailable = sum(row[3] == "unavailable" and row[1] != "not-installed" for row in rows)
        count = sum(row[1] != "not-installed" for row in rows)
        state.update(CHECK_STATUS="ok" if not unavailable else "partial",
                     UPDATE_AVAILABLE="yes" if outdated else "unknown" if unavailable or not refresh else "no",
                     OUTDATED_COUNT=outdated, UNAVAILABLE_COUNT=unavailable, INSTALLED_COUNT=count,
                     LAST_SUCCESSFUL_CHECK=now, LAST_ERROR="Candidatas no disponibles" if unavailable else "",
                     LATEST_VERSION=f"{outdated} paquetes APT", CURRENT_VERSION=f"{count} paquetes Harresi instalados")
        report = "PACKAGE\tINSTALLED_VERSION\tLATEST_VERSION\tUPDATE_AVAILABLE\n"
        report += "".join("\t".join(row) + "\n" for row in rows)
        atomic(STATE_DIR / "update-packages.tsv", report)
        save_state(state)
        print(f"Comprobación completada: {outdated} actualizaciones; {unavailable} candidatas no disponibles. Metadatos: {state['METADATA_STATUS']}.")
        if unavailable:
            raise RuntimeError("Comprobación parcial: faltan versiones candidatas para paquetes instalados.")
    except (RuntimeError, OSError, subprocess.TimeoutExpired) as exc:
        if state.get("CHECK_STATUS") != "partial":
            state.update(CHECK_STATUS="unavailable", UPDATE_AVAILABLE="unknown", LAST_ERROR=" ".join(str(exc).split())[:2000])
            save_state(state)
        raise


def status():
    state = settings(STATE_DIR / "update.state")
    if not state:
        print("Comprobación de actualizaciones no disponible: todavía no hay un informe.")
        return
    checked = state.get("LAST_SUCCESSFUL_CHECK", "0")
    now = int(time.time())
    stale = not checked.isdigit() or not 0 < int(checked) <= now or now - int(checked) > 86400
    print(f"Estado de comprobación: {state.get('CHECK_STATUS', 'unavailable')}; "
          f"metadatos: {state.get('METADATA_STATUS', 'stale')}; "
          f"informe {'obsoleto' if stale else 'reciente'}.")
    print(f"Último intento (epoch): {state.get('LAST_CHECK', '0')}; última comprobación completada: {checked}.")
    print(f"Actualizaciones: {state.get('UPDATE_AVAILABLE', 'unknown')}; paquetes: {state.get('OUTDATED_COUNT', '?')}.")
    if state.get("LAST_ERROR"):
        print("Error: " + state["LAST_ERROR"])
    print("harresi_updater.timer comprueba disponibilidad; la instalación requiere una acción del administrador.")


def snapshot_services():
    saved = {}
    for service in SERVICES:
        enabled_result = command("systemctl", "is-enabled", service, check=False)
        enabled = enabled_result.stdout.strip()
        active = command("systemctl", "is-active", service, check=False).stdout.strip()
        # systemctl prints missing units on stderr on some shipped releases.
        if not enabled and enabled_result.returncode and any(
            marker in enabled_result.stderr.lower() for marker in ("does not exist", "no such file", "not found")
        ):
            enabled = "not-found"
        if enabled not in ("enabled", "disabled", "masked", "not-found"):
            raise RuntimeError(f"No se puede preservar el estado de {service}: {enabled}")
        if enabled != "not-found" and active not in ("active", "inactive", "failed"):
            raise RuntimeError(f"El servicio {service} tiene un estado transitorio o desconocido: {active}; vuelva a intentarlo.")
        if active == "failed":
            print(f"Advertencia: {service} ya estaba fallido antes de la instalación.", file=sys.stderr)
        saved[service] = {"enabled": enabled, "active": active == "active"}
    return saved


def restore_services(saved):
    # The monitor may have been restarted by a package script. Quiesce it
    # before restoring selections so it cannot revive an intentionally
    # live-stopped engine using the old runtime intention.
    monitor = saved.get("suricata-monitor")
    if monitor and monitor["enabled"] != "not-found":
        command("systemctl", "stop", "suricata-monitor")
    for service, state in saved.items():
        if state["enabled"] == "not-found":
            continue
        if state["enabled"] == "masked":
            command("systemctl", "mask", service)
        else:
            command("systemctl", "unmask", service)
            command("systemctl", "enable" if state["enabled"] == "enabled" else "disable", service)
    # Stop competing or previously stopped writers before starting the saved
    # selection. Restore boot enablement independently from live activity.
    for service, state in saved.items():
        if service != "suricata-monitor" and state["enabled"] != "not-found" and not state["active"]:
            command("systemctl", "stop", service)
    # The decrypted engine depends on the proxy listener. No inactive snapshot
    # unit is implicitly started; the monitor waits for runtime publication.
    start_order = ("sslproxyd", "suricata_mitm", "suricata_ids", "suricata_idps", "suricata-aggregator")
    for service in start_order:
        state = saved.get(service)
        if state and state["enabled"] != "not-found" and state["active"]:
            command("systemctl", "start", service)
    helper = os.environ.get("HARRESI_SERVICE_HELPER", "/usr/local/sbin/harresi-services")
    command(helper, "restore-selected")
    # restore-selected publishes the intended runtime state and verifies the
    # engines/listener before reopening traffic. A failure leaves monitoring
    # stopped and propagates the recovery error instead of reviving services.
    if monitor and monitor["enabled"] != "not-found" and monitor["active"]:
        command("systemctl", "start", "suricata-monitor")


def install_version(package, version):
    validate_package(package)
    if not re.fullmatch(r"[0-9][A-Za-z0-9.+:~_-]*", version) or version not in versions(package):
        raise ValueError("La versión seleccionada no está disponible en APT; refresque la información.")
    current = installed(package)
    saved = snapshot_services()
    recovery = STATE_DIR / "apt-recovery.json"
    atomic(recovery, json.dumps({"package": package, "previous": current, "requested": version,
                                "services": saved}, indent=2) + "\n", 0o600)
    error = None
    try:
        command("apt-get", "-o", "Dpkg::Options::=--force-confdef", "-o", "Dpkg::Options::=--force-confold",
                "install", "--no-remove", "--allow-downgrades", "-y", f"{package}={version}")
        actual = installed(package)
        if actual != version:
            raise RuntimeError(f"Versión instalada inesperada: {actual}; se solicitó {version}.")
        print(f"Versión instalada y verificada: {package}={actual}.")
    except (RuntimeError, OSError, subprocess.TimeoutExpired) as exc:
        error = exc
    try:
        restore_services(saved)
    except (RuntimeError, OSError, subprocess.TimeoutExpired) as exc:
        raise RuntimeError(f"La recuperación de la selección de servicios falló: {exc}. Detalles: {recovery}") from error
    if error:
        raise RuntimeError(f"La instalación falló: {error}. Selección de servicios restaurada; "
                           f"APT puede haber instalado dependencias parcialmente. Recuperación: {recovery}") from error
    print("Selección operativa de servicios conservada. Reversión: seleccione una versión anterior disponible en este mismo menú.")
    try:
        check_updates()
    except (RuntimeError, OSError, subprocess.TimeoutExpired) as exc:
        # The package and service restoration succeeded; a failed subsequent
        # availability query must not misreport that installation as failed.
        print(f"Advertencia: instalación verificada; comprobación APT posterior no disponible: {exc}", file=sys.stderr)


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    subs = parser.add_subparsers(dest="action", required=True)
    check = subs.add_parser("check")
    check.add_argument("--automatic", action="store_true")
    subs.add_parser("status")
    ver = subs.add_parser("versions")
    ver.add_argument("package")
    inst = subs.add_parser("install")
    inst.add_argument("package")
    inst.add_argument("version")
    args = parser.parse_args()
    if args.action == "status":
        status()
    elif args.action == "versions":
        print("\n".join(versions(args.package)))
    else:
        if os.geteuid() != 0 and not os.environ.get("HARRESI_APT_TEST"):
            raise PermissionError("Esta acción requiere privilegios de administrador.")
        STATE_DIR.mkdir(parents=True, exist_ok=True)
        with (STATE_DIR / ".apt.lock").open("a") as lock:
            fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
            if args.action == "check":
                check_updates(args.automatic)
            else:
                install_version(args.package, args.version)


if __name__ == "__main__":
    try:
        main()
    except (ValueError, RuntimeError, OSError, subprocess.TimeoutExpired) as failure:
        print(f"Error APT: {failure}", file=sys.stderr)
        sys.exit(1)
