#!/usr/bin/python3 -I
# SPDX-License-Identifier: LicenseRef-CMSD-1.0
# Copyright (c) 2026 CyberMind — Gérald Kerma <devel@cybermind.fr>
# Source-Disclosed License — All rights reserved except as expressly granted.
# See LICENCE-CMSD-1.0.md for terms.
"""SecuBox-Deb :: secubox-reparerctl — bouton « Réparer » de la page Santé (#3628).

POURQUOI UN CTL ROOT. L'API health-doctor tourne en `secubox` (dans l'agrégateur) : elle ne peut
ni relancer une unité ni terminer un dpkg interrompu. Elle DÉPOSE une demande dans
/run/secubox/health-reparer ; l'unité root secubox-reparer.path la voit et lance ce script
(secubox-reparer.service). Ni sudo ni polkit.

ENTRÉE NON FIABLE. Le dossier de demandes est inscriptible par le groupe secubox : chaque entrée
est ouverte PAR DESCRIPTEUR relatif au dossier (lui-même ouvert sans suivre de lien), sans suivre
de lien, sans bloquer (un FIFO ne fige rien), fstat exige un fichier ordinaire, 512 octets au
plus. Le contenu n'est jamais recopié dans un journal : seulement le nom ou « invalide ».

LISTE FERMÉE DE FAIT. Une demande ne vaut que pour une unité `secubox-<id>.service` CHARGÉE et À
L'ÉTAT `failed`, hors REFUS (unités dont l'arrêt est une sécurité). Étapes : (1) une configuration
dpkg interrompue est terminée (cas de la mise à jour automatique coupée, #3606) — si une mise à
jour tient le verrou, on répond « réessayer » sans attendre ; (2) reset-failed ; (3) démarrage
sans attendre la fin (une tâche oneshot comme majauto peut durer) ; (4) relecture. Chaque
réparation est écrite dans /var/log/secubox/audit.log.

Verbes : reparer <id> [acteur] · process-ops · status · version
"""
from __future__ import annotations

import fcntl
import json
import os
import re
import shutil
import stat
import subprocess
import sys
import tempfile
import time
from datetime import datetime, timezone

VERSION = "1.1.0"
ENV = os.environ.get
SPOOL = ENV("SECUBOX_REPARER_SPOOL", "/run/secubox/health-reparer")
ETAT = ENV("SECUBOX_REPARER_ETAT", "/var/lib/secubox-health-reparer/reparer.json")
JOURNAL = ENV("SECUBOX_REPARER_JOURNAL", "/var/log/secubox/reparer.log")
AUDIT = ENV("SECUBOX_AUDIT_LOG", "/var/log/secubox/audit.log")
VERROU = ENV("SECUBOX_REPARER_VERROU", "/run/secubox-reparer/verrou")
DPKG_UPDATES = ENV("SECUBOX_REPARER_DPKG_UPDATES", "/var/lib/dpkg/updates")
DPKG_VERROU = ENV("SECUBOX_REPARER_DPKG_VERROU", "/var/lib/dpkg/lock-frontend")
SYSTEMCTL = ENV("SECUBOX_REPARER_SYSTEMCTL", "systemctl")
DPKG = ENV("SECUBOX_REPARER_DPKG", "dpkg")
ATTENTE_S = float(ENV("SECUBOX_REPARER_ATTENTE_S", "20"))
PAS_S = float(ENV("SECUBOX_REPARER_PAS_S", "1"))

ID_RE = re.compile(r"[a-z0-9][a-z0-9-]{0,62}")
DEMANDE_RE = re.compile(r"reparer ([a-z0-9][a-z0-9-]{0,62}) ([A-Za-z0-9@._:-]{1,64})\n?")
# Unités dont l'arrêt est voulu ou est une sécurité : jamais relancées depuis une page.
REFUS = frozenset({"lan-dhcp", "lan-dhcp-garde", "lan-dhcp-surveille", "netmodes-retour-boot", "reparer"})
REFUS_PREFIXES = ("mobile",)
TAILLE_MAX = 512
TEMP_GRACE_S = 60          # un nom caché plus récent est une demande en cours d'écriture (API)


def _maintenant() -> str:
    return datetime.now(timezone.utc).isoformat(timespec="seconds")


def _ajout(chemin: str, ligne: str, mode: int = 0o640) -> None:
    """Ajout seul, sans suivre de lien (root écrit là où un autre compte pourrait poser un lien)."""
    try:
        os.makedirs(os.path.dirname(chemin), exist_ok=True)
        fd = os.open(chemin, os.O_WRONLY | os.O_APPEND | os.O_CREAT | os.O_NOFOLLOW | os.O_CLOEXEC, mode)
        with os.fdopen(fd, "a", encoding="utf-8") as f:
            f.write(ligne + "\n")
    except OSError as e:
        print(f"{chemin} non écrit ({e.__class__.__name__}) : {ligne}", file=sys.stderr)


def journal(msg: str) -> None:
    _ajout(JOURNAL, f"{_maintenant()} {msg}")


def _acteur(brut: str) -> str:
    return re.sub(r"[^A-Za-z0-9@._:-]", "", brut or "")[:64] or "inconnu"


def consigne(module: str, acteur: str, ok: bool, phase: str, message: str, debut: int, etapes: list[str]) -> None:
    """État ATOMIQUE (lisible par l'API, autre compte) ; audit à la fin de chaque réparation."""
    entree = {"module": module, "acteur": acteur, "ok": ok, "phase": phase, "message": message,
              "debut": debut, "fin": int(time.time()), "etapes": list(etapes)}
    dossier = os.path.dirname(ETAT)
    os.makedirs(dossier, exist_ok=True)
    try:
        with open(ETAT, encoding="utf-8") as f:
            etat = json.load(f)
        if not isinstance(etat, dict) or not isinstance(etat.get("modules"), dict):
            raise ValueError("forme")
    except FileNotFoundError:
        etat = {"modules": {}}
    except (OSError, ValueError) as e:
        journal(f"état illisible, repris à zéro ({e.__class__.__name__})")
        etat = {"modules": {}}
    etat["modules"][module] = entree
    garde = sorted(etat["modules"].items(), key=lambda kv: kv[1].get("fin", 0))[-50:]
    fd, tmp = tempfile.mkstemp(dir=dossier, prefix=".reparer-")
    try:
        with os.fdopen(fd, "w", encoding="utf-8") as f:
            json.dump({"modules": dict(garde), "maj": entree["fin"]}, f, ensure_ascii=False)
        os.chmod(tmp, 0o644)
        os.replace(tmp, ETAT)
    except OSError as e:
        journal(f"état non écrit ({e.__class__.__name__})")
        try:
            os.unlink(tmp)
        except OSError:
            pass
    if phase == "fini":
        _ajout(AUDIT, json.dumps({"ts": _maintenant(), "event": "sante_reparation", "module": module,
                                  "unite": f"secubox-{module}.service", "acteur": acteur, "ok": ok,
                                  "message": message, "etapes": list(etapes)}, ensure_ascii=True))


def _prop(unite: str, nom: str) -> str:
    try:
        r = subprocess.run([SYSTEMCTL, "show", "-p", nom, "--value", "--", unite],
                           capture_output=True, text=True, timeout=30)
        return (r.stdout.splitlines() or [""])[0].strip()
    except (OSError, subprocess.SubprocessError):
        return ""


def _systemctl(*args: str) -> bool:
    try:
        r = subprocess.run([SYSTEMCTL, *args], capture_output=True, text=True, timeout=60)
    except (OSError, subprocess.SubprocessError) as e:
        journal(f"systemctl {args[0]} : {e.__class__.__name__}")
        return False
    if r.returncode:
        journal(f"systemctl {args[0]} rc={r.returncode} : {r.stderr.strip()[:300]}")
    return r.returncode == 0


def _dpkg_interrompu() -> bool:
    try:
        if os.listdir(DPKG_UPDATES):
            return True
    except OSError:
        pass
    try:
        r = subprocess.run([DPKG, "--audit"], capture_output=True, text=True, timeout=120)
        return bool(r.stdout.strip())
    except (OSError, subprocess.SubprocessError):
        return False


def _dpkg_occupe() -> bool:
    """Le verrou frontal est-il tenu (apt ou dpkg en cours) ? On le teste sans l'attendre."""
    try:
        fd = os.open(DPKG_VERROU, os.O_RDWR | os.O_NOFOLLOW | os.O_CLOEXEC)
    except FileNotFoundError:
        return False
    except OSError:
        return True
    try:
        fcntl.lockf(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
        fcntl.lockf(fd, fcntl.LOCK_UN)
        return False
    except OSError:
        return True
    finally:
        os.close(fd)


def _dpkg_terminer() -> bool:
    """Jamais de délai ni de kill : une configuration coupée est pire qu'une configuration lente."""
    try:
        r = subprocess.run([DPKG, "--force-confold", "--force-confdef", "--configure", "-a"],
                           capture_output=True, text=True)
    except OSError as e:
        journal(f"dpkg --configure -a : {e.__class__.__name__}")
        return False
    for ligne in (r.stdout + r.stderr).splitlines()[-40:]:
        journal(f"dpkg: {ligne[:300]}")
    return r.returncode == 0


def reparer(module: str, acteur_brut: str = "") -> tuple[bool, str]:
    acteur = _acteur(acteur_brut)
    if not ID_RE.fullmatch(module or ""):
        return False, "identifiant de module invalide"
    unite = f"secubox-{module}.service"
    debut = int(time.time())
    etapes: list[str] = []

    def fin(ok: bool, message: str) -> tuple[bool, str]:
        consigne(module, acteur, ok, "fini", message, debut, etapes)
        journal(f"{module} : {'réparé' if ok else 'non réparé'} — {message}")
        return ok, message

    if module in REFUS or module.startswith(REFUS_PREFIXES):
        return fin(False, f"{unite} ne se relance pas depuis la page : son arrêt est voulu ou protège la box")
    load = _prop(unite, "LoadState")
    if load != "loaded":
        return fin(False, f"unité {unite} introuvable : rien à réparer")
    avant = _prop(unite, "ActiveState")
    if avant != "failed":
        return fin(False, f"{unite} n'est pas en panne ({avant or 'état inconnu'}) : rien n'a été relancé")
    consigne(module, acteur, False, "en_cours", "réparation en cours", debut, etapes)
    journal(f"{module} : réparation demandée par {acteur}")

    if _dpkg_interrompu():
        if _dpkg_occupe():
            return fin(False, "une mise à jour est en cours (dpkg occupé) : réessayer dans quelques minutes")
        consigne(module, acteur, False, "en_cours", "configuration dpkg interrompue : reprise", debut, etapes)
        if not _dpkg_terminer():
            etapes.append(f"dpkg : configuration en échec (voir {JOURNAL})")
            return fin(False, "dpkg n'a pas pu terminer sa configuration ; service non relancé")
        etapes.append("dpkg : configuration terminée")

    _systemctl("reset-failed", "--", unite)
    etapes.append("échec effacé (reset-failed)")
    # LA MINUTERIE QUI LE DÉCLENCHE (#3692). Une unité de minuterie en échec laisse souvent sa minuterie arrêtée
    # (mail-imap-sync sur gk2 : minuterie morte depuis 6 jours) ; relancer le service seul ne la remettait pas en route.
    # Seulement une minuterie ACTIVÉE (enabled) : une minuterie désactivée l'a été volontairement.
    for m in _prop(unite, "TriggeredBy").split():
        if m.endswith(".timer") and _prop(m, "UnitFileState") == "enabled" \
                and _prop(m, "ActiveState") in ("inactive", "failed"):
            _systemctl("reset-failed", "--", m)
            etapes.append(f"minuterie {m} relancée" if _systemctl("start", "--", m) else f"minuterie {m} : relance refusée")
    if not _systemctl("start", "--no-block", "--", unite):
        etapes.append("démarrage refusé par systemd")
        return fin(False, f"systemd a refusé de démarrer {unite}")
    etapes.append("démarrage lancé")

    t = 0.0
    while True:
        etat, sub, result = _prop(unite, "ActiveState"), _prop(unite, "SubState"), _prop(unite, "Result")
        if etat == "active":
            return fin(True, f"{unite} relancé ({sub})")
        if etat == "failed":
            return fin(False, f"{unite} retombe en panne ({result}) : voir journalctl -u {unite}")
        if etat == "inactive" and result == "success" and t > 0:
            return fin(True, f"{unite} a terminé sa tâche sans erreur")
        if t >= ATTENTE_S:
            if etat == "activating":
                return fin(True, f"{unite} relancé : tâche en cours d'exécution")
            return fin(False, f"{unite} : état {etat}/{sub} après {int(ATTENTE_S)} s")
        time.sleep(PAS_S)
        t += PAS_S


def _ouvre_spool() -> int:
    fd = os.open(SPOOL, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW | os.O_CLOEXEC)
    st = os.fstat(fd)
    # Root possède le dossier, personne d'autre que le groupe n'y écrit (tmpfiles : 0770 root:secubox).
    if st.st_mode & 0o002 or (os.geteuid() == 0 and st.st_uid != 0):
        os.close(fd)
        raise PermissionError(f"{SPOOL} : propriétaire ou droits inattendus")
    return fd


def _lit_demande(dfd: int, nom: str) -> str | None:
    try:
        fd = os.open(nom, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK | os.O_CLOEXEC, dir_fd=dfd)
    except OSError:
        return None
    try:
        if not stat.S_ISREG(os.fstat(fd).st_mode):
            return None
        brut = os.read(fd, TAILLE_MAX + 1)
    except OSError:
        return None
    finally:
        os.close(fd)
    if len(brut) > TAILLE_MAX:
        return None
    try:
        return brut.decode("ascii")
    except UnicodeDecodeError:
        return None


def _retire(dfd: int, nom: str) -> None:
    try:
        st = os.stat(nom, dir_fd=dfd, follow_symlinks=False)
        if stat.S_ISDIR(st.st_mode):
            shutil.rmtree(nom, dir_fd=dfd)
        else:
            os.unlink(nom, dir_fd=dfd)
    except OSError as e:
        journal(f"entrée {nom!r} non retirée ({e.__class__.__name__})")


def _clore_interrompues() -> None:
    """Verrou tenu = aucun autre passage : un « en_cours » restant vient d'un passage mort (redémarrage,
    arrêt en plein dpkg). Il est clos et audité, sinon l'API répondrait 409 pour toujours."""
    try:
        with open(ETAT, encoding="utf-8") as f:
            mods = json.load(f).get("modules") or {}
    except (OSError, ValueError, AttributeError):
        return
    for module, e in list(mods.items()):
        if isinstance(e, dict) and e.get("phase") == "en_cours" and ID_RE.fullmatch(str(module)):
            consigne(module, _acteur(str(e.get("acteur", ""))), False, "fini",
                     "réparation interrompue (redémarrage ou arrêt du service) : la relancer", int(e.get("debut") or 0),
                     [str(x)[:200] for x in (e.get("etapes") or []) if isinstance(x, str)])


def process_ops() -> int:
    """Draine TOUT le dossier (une entrée laissée relancerait l'unité .path en boucle)."""
    os.makedirs(os.path.dirname(VERROU), exist_ok=True)
    vfd = os.open(VERROU, os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW | os.O_CLOEXEC, 0o600)
    try:
        fcntl.flock(vfd, fcntl.LOCK_EX | fcntl.LOCK_NB)
    except OSError:
        print("reparerctl: un passage est déjà en cours", file=sys.stderr)
        return 0
    fait = 0
    _clore_interrompues()
    dfd = _ouvre_spool()
    try:
        for _tour in range(20):
            noms = sorted(os.listdir(dfd))
            attente = False
            for nom in noms:
                if nom.startswith("."):
                    # Demande en cours d'écriture par l'API (nom caché puis rename) : on lui laisse le temps.
                    try:
                        age = time.time() - os.stat(nom, dir_fd=dfd, follow_symlinks=False).st_mtime
                    except OSError:
                        continue
                    if 0 <= age < TEMP_GRACE_S:     # une date future (touch -d) ne protège rien
                        attente = True
                        continue
                    _retire(dfd, nom)
                    journal(f"entrée cachée abandonnée retirée : {nom!r}")
                    continue
                contenu = _lit_demande(dfd, nom) if nom.endswith(".demande") else None
                _retire(dfd, nom)            # retirée AVANT d'agir : une demande qui plante ne boucle pas
                m = DEMANDE_RE.fullmatch(contenu or "")
                if not m:
                    journal(f"demande invalide ignorée : {nom[:80]!r}")
                    continue
                reparer(m.group(1), m.group(2))
                fait += 1
            if not attente:
                break
            time.sleep(0.25)
    finally:
        os.close(dfd)
    print(json.dumps({"ok": True, "traitees": fait}))
    return 0


def main(argv: list[str]) -> int:
    verbe = argv[1] if len(argv) > 1 else "help"
    if verbe == "reparer":
        if len(argv) < 3:
            print(json.dumps({"ok": False, "message": "identifiant manquant"}))
            return 2
        if not ID_RE.fullmatch(argv[2]):
            print(json.dumps({"ok": False, "message": "identifiant de module invalide"}))
            return 2
        ok, msg = reparer(argv[2], argv[3] if len(argv) > 3 else "")
        print(json.dumps({"ok": ok, "module": argv[2], "message": msg}, ensure_ascii=False))
        return 0 if ok else 1
    if verbe == "process-ops":
        return process_ops()
    if verbe == "status":
        try:
            with open(ETAT, encoding="utf-8") as f:
                print(f.read())
        except OSError:
            print('{"modules":{}}')
        return 0
    if verbe == "version":
        print(json.dumps({"ok": True, "version": VERSION}))
        return 0
    print(__doc__)
    return 0


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