#!/usr/bin/python3
# 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-nac-partages — un appareil du LAN distribué à un pair du maillage (#4218).

Sur la SOURCE (la box qui a l'appareil, ex. gk2) — root, étroit, lancé par secubox-nac-partages.path :
  appliquer        relit /etc/secubox/nac-partages.toml (écrit par l'API NAC), le REVALIDE, garde les
                   seuls partages actifs dont le pair est un pair de wg-mesh, rend la table
                   `inet secubox_nac_partages` (/etc/nftables.d/secubox-nac-partages.nft), `nft -c` puis
                   bascule ; chaque ouverture / fermeture écrite dans /var/log/secubox/audit.log.
                   Fichier invalide : rien ne change, refus audité.
  etat             partages et renvois appliqués (JSON)
  partage-poser <nom> <ip-appareil> <ipp|http|https> <ip-maillée-du-pair> [port-relais]
                   déclare (actif) un partage : pair -> <IP maillée d'ici>:port-relais -> appareil:service
  renvoi-poser <nom> <port-entree> <ip-maillée-du-pair> [port-du-pair]      (#4239, #4246)
                   déclare (actif) un renvoi : port d'arrivée côté LAN (8000-8999) -> pair:port (443 par défaut ;
                   80, 443 ou l'entrée maillée dédiée du pair, 1024-65535 hors 8085),
                   masquerade pour que la réponse revienne par cette box
  retirer <nom>    retire le partage ou le renvoi <nom>
                   Ces trois commandes écrivent le TOML (double tampon), auditent, puis appliquent.

Sur le PAIR (la box du client, ex. gk7) — root, à la main :
  file-poser <nom> <ip-maillée-de-la-source> <port-relais> [--lan <interface>]
                   file CUPS sans pilote (IPP Everywhere) vers ipp://<ip>:<port>/ipp/print, partagée
                   au LAN du client (cupsd ; annonce mDNS par avahi) ; 631/tcp ouvert au seul
                   sous-réseau de <interface> (défaut : interface de la route par défaut).
  file-retirer <nom>
                   retire la file ; à la dernière, ferme 631 et arrête le partage CUPS.
"""
from __future__ import annotations

import importlib.util
import ipaddress
import json
import os
import re
import shutil
import subprocess
import sys
import time
from pathlib import Path

ESSAI = os.getuid() != 0 and bool(os.environ.get("NAC_PARTAGES_ESSAI"))
API = Path(os.environ.get("NAC_PARTAGES_API", "/usr/lib/secubox/nac/api/partages.py"))
REGLES = Path(os.environ.get("NAC_PARTAGES_NFT", "/etc/nftables.d/secubox-nac-partages.nft"))
ETAT_RENVOIS = Path(os.environ.get("NAC_PARTAGES_ETAT_RENVOIS", "/var/lib/secubox/nac/renvois-appliques.json"))
ETAT = Path(os.environ.get("NAC_PARTAGES_ETAT", "/var/lib/secubox/nac/partages-appliques.json"))
AUDIT = Path(os.environ.get("NAC_PARTAGES_AUDIT", "/var/log/secubox/audit.log"))
FILES = Path(os.environ.get("NAC_PARTAGES_FILES", "/var/lib/secubox/nac/files-partagees.json"))
CUPS_NFT = Path(os.environ.get("NAC_PARTAGES_CUPS_NFT", "/etc/nftables.d/secubox-nac-cups.nft"))
CHEMIN_IPP = "/ipp/print"   # Brother HL-L8250CDN : rp=ipp/print (mDNS) et Get-Printer-Attributes 200 (sondé le 02/12)
COMMENTAIRE_CUPS = "secubox-nac-cups"
PAQUETS_PAIR = "cups cups-filters avahi-daemon"

_spec = importlib.util.spec_from_file_location("secubox_nac_partages", API)
P = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(P)


def lancer(cmd: list[str], entree: str | None = None) -> subprocess.CompletedProcess:
    """Seul point d'appel système (remplacé dans les tests)."""
    return subprocess.run(cmd, input=entree, capture_output=True, text=True, timeout=60)


def audit(evenement: str, **champs) -> None:
    ligne = {"ts": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), "module": "nac",
             "evenement": evenement, **champs}
    try:
        with AUDIT.open("a") as f:
            f.write(json.dumps(ligne, ensure_ascii=False) + "\n")
    except OSError:
        pass


def meurt(msg: str) -> None:
    print(f"[nac-partages] ERREUR : {msg}", file=sys.stderr)
    sys.exit(1)


def _ecrire_json(chemin: Path, donnees) -> None:
    tmp = chemin.with_name(chemin.name + ".sbxtmp")
    tmp.write_text(json.dumps(donnees, ensure_ascii=False, indent=1) + "\n")
    os.replace(tmp, chemin)


def _lire_json(chemin: Path, defaut):
    try:
        return json.loads(chemin.read_text())
    except (OSError, ValueError):
        return defaut


def reseaux_wg() -> list[ipaddress.IPv4Network]:
    """allowed-ips de wg-mesh sur ce nœud."""
    r = lancer(["wg", "show", P.INTERFACE_MAILLAGE, "allowed-ips"])
    nets = []
    for mot in (r.stdout or "").split() if r.returncode == 0 else []:
        try:
            nets.append(ipaddress.IPv4Network(mot, strict=False))
        except ValueError:
            continue
    return nets


# ── SOURCE ─────────────────────────────────────────────────────────────────────
def cmd_appliquer() -> int:
    try:
        voulus = P.lire()
        renvois = P.lire_renvois()
    except ValueError as e:
        audit("nac_partages_refuse", raison=str(e))
        meurt(f"{e} — table vivante conservée")
    # Un pair est joignable par le maillage s'il est couvert par un allowed-ips de wg-mesh : pair direct (/32) ou relayé par un
    # autre nœud (gk2 couvre 10.10.0.0/24, #4242). Jamais une route large (préfixe < /16) : elle couvrirait n'importe quoi.
    reseaux = [n for n in reseaux_wg() if n.prefixlen >= 16]

    def joignable(ip: str) -> bool:
        a = ipaddress.IPv4Address(ip)
        return any(a in n for n in reseaux)
    retenus = []
    for p in voulus:
        if p["actif"] and not joignable(p["pair"]):
            audit("nac_partage_pair_absent", nom=p["nom"], pair=p["pair"])
            print(f"[nac-partages] {p['nom']} : {p['pair']} n'est pas joignable par wg-mesh — non ouvert")
            continue
        retenus.append(p)
    renvois_retenus = []
    for r in renvois:
        if r["actif"] and not joignable(r["pair"]):
            audit("nac_renvoi_pair_absent", nom=r["nom"], pair=r["pair"])
            print(f"[nac-partages] renvoi {r['nom']} : {r['pair']} n'est pas joignable par wg-mesh — non ouvert")
            continue
        renvois_retenus.append(r)
    rendu = P.rendu_nft(retenus, renvois_retenus)
    table = f"inet {P.TABLE}"
    if not rendu:
        lancer(["nft", "delete", "table", "inet", P.TABLE])
        REGLES.unlink(missing_ok=True)
    else:
        # « table {} » + « delete table » + la table : une transaction, sans instant où elle manque.
        tmp = REGLES.with_name(REGLES.name + ".sbxtmp")
        tmp.write_text("# secubox-nac-partages (#4218) : régénéré depuis /etc/secubox/nac-partages.toml, "
                       f"ne pas éditer.\ntable {table} {{}}\ndelete table {table}\n{rendu}")
        if lancer(["nft", "-c", "-f", str(tmp)]).returncode != 0:
            tmp.unlink(missing_ok=True)
            audit("nac_partages_nft_refuse")
            meurt("nft -c refuse la table des partages — ancien fichier et table vivante conservés")
        os.replace(tmp, REGLES)
        if lancer(["nft", "-f", str(REGLES)]).returncode != 0:
            audit("nac_partages_nft_echec")
            meurt(f"nft a refusé {REGLES} à chaud")
    avant = {P.cle(p) for p in _lire_json(ETAT, []) if isinstance(p, dict) and "nom" in p}
    apres = [p for p in retenus if p["actif"]]
    for p in apres:
        if P.cle(p) not in avant:
            audit("nac_partage_ouvert", nom=p["nom"], appareil=p["appareil"], service=p["service"],
                  pair=p["pair"], port_relais=p["port_relais"])
    cles_apres = {P.cle(p) for p in apres}
    for k in sorted(avant - cles_apres):
        nom, app, service, pair, port = k.split("|")
        audit("nac_partage_ferme", nom=nom, appareil=app, service=service, pair=pair, port_relais=int(port))
    _ecrire_json(ETAT, apres)
    rv_avant = {P.cle_renvoi(r) for r in _lire_json(ETAT_RENVOIS, []) if isinstance(r, dict) and "nom" in r}
    rv_apres = [r for r in renvois_retenus if r["actif"]]
    for r in rv_apres:
        if P.cle_renvoi(r) not in rv_avant:
            audit("nac_renvoi_ouvert", nom=r["nom"], port_entree=r["port_entree"], pair=r["pair"],
                  port_pair=r["port_pair"])
    for k in sorted(rv_avant - {P.cle_renvoi(r) for r in rv_apres}):
        nom, entree, pair, port_pair = k.split("|")
        audit("nac_renvoi_ferme", nom=nom, port_entree=int(entree), pair=pair, port_pair=int(port_pair))
    _ecrire_json(ETAT_RENVOIS, rv_apres)
    print(f"[nac-partages] {len(apres)} partage(s), {len(rv_apres)} renvoi(s) ouvert(s)")
    return 0


def cmd_etat() -> int:
    print(json.dumps({"partages": _lire_json(ETAT, []), "renvois": _lire_json(ETAT_RENVOIS, [])},
                     ensure_ascii=False, indent=1))
    return 0


def _entier(v: str, champ: str) -> int:
    if not re.fullmatch(r"[0-9]{1,5}", v or ""):
        meurt(f"{champ} : entier attendu, pas « {v} »")
    return int(v)


def _declarer(partages: list[dict], renvois: list[dict], evenement: str, **champs) -> int:
    try:
        P.ecrire(partages, renvois=renvois)
    except ValueError as e:
        audit(evenement + "_refuse", raison=str(e), **champs)
        meurt(str(e))
    audit(evenement, **champs)
    return cmd_appliquer()


def _actuels() -> tuple[list[dict], list[dict]]:
    try:
        return P.lire(), P.lire_renvois()
    except ValueError as e:
        meurt(f"{e} — rien n'est changé")


def cmd_partage_poser(args: list[str]) -> int:
    if len(args) not in (4, 5):
        meurt("usage : partage-poser <nom> <ip-appareil> <ipp|http|https> <ip-maillée-du-pair> [port-relais]")
    partages, renvois = _actuels()
    nouveau = {"nom": args[0], "appareil": args[1], "service": args[2], "pair": args[3], "actif": True}
    if len(args) == 5:
        nouveau["port_relais"] = _entier(args[4], "port-relais")
    nom = args[0].strip().lower()
    if any(r["nom"] == nom for r in renvois):
        meurt(f"« {nom} » est déjà un renvoi")
    return _declarer([p for p in partages if p["nom"] != nom] + [nouveau], renvois,
                     "nac_partage_declare", nom=nom, appareil=args[1], service=args[2], pair=args[3])


def cmd_renvoi_poser(args: list[str]) -> int:
    if len(args) not in (3, 4):
        meurt("usage : renvoi-poser <nom> <port-entree> <ip-maillée-du-pair> [port-du-pair]")
    partages, renvois = _actuels()
    nom = args[0].strip().lower()
    if any(p["nom"] == nom for p in partages):
        meurt(f"« {nom} » est déjà un partage")
    nouveau = {"nom": args[0], "port_entree": _entier(args[1], "port-entree"), "pair": args[2], "actif": True,
               "port_pair": _entier(args[3], "port du pair") if len(args) == 4 else 443}
    return _declarer(partages, [r for r in renvois if r["nom"] != nom] + [nouveau], "nac_renvoi_declare",
                     nom=nom, port_entree=nouveau["port_entree"], pair=args[2], port_pair=nouveau["port_pair"])


def cmd_retirer(args: list[str]) -> int:
    if len(args) != 1:
        meurt("usage : retirer <nom>")
    nom = args[0].strip().lower()
    partages, renvois = _actuels()
    p2 = [p for p in partages if p["nom"] != nom]
    r2 = [r for r in renvois if r["nom"] != nom]
    if len(p2) == len(partages) and len(r2) == len(renvois):
        meurt(f"« {nom} » inconnu")
    return _declarer(p2, r2, "nac_partage_renvoi_retire", nom=nom)


# ── PAIR ───────────────────────────────────────────────────────────────────────
def chaine_input() -> str | None:
    for t in ("secubox_filter", "filter"):
        if lancer(["nft", "list", "chain", "inet", t, "input"]).returncode == 0:
            return t
    return None


def lan_de(interface: str | None) -> tuple[str, str]:
    """(interface, sous-réseau IPv4) du LAN du client."""
    if not interface:
        r = lancer(["ip", "-4", "route", "show", "default"])
        m = re.search(r"\bdev (\S+)", r.stdout or "")
        if not m:
            meurt("pas de route par défaut : préciser --lan <interface>")
        interface = m.group(1)
    if not re.fullmatch(r"[A-Za-z0-9_.@-]{1,15}", interface) or interface.startswith("wg"):
        meurt(f"interface LAN invalide « {interface} »")
    r = lancer(["ip", "-4", "-o", "addr", "show", "dev", interface])
    m = re.search(r"\binet (\d+\.\d+\.\d+\.\d+/\d+)", r.stdout or "")
    if not m:
        meurt(f"aucune adresse IPv4 sur {interface}")
    reseau = ipaddress.IPv4Network(m.group(1), strict=False)
    if not reseau.is_private or reseau.overlaps(P.MAILLAGE):
        meurt(f"{reseau} n'est pas un LAN privé hors maillage")
    return interface, str(reseau)


def regle_cups(interface: str, reseau: str) -> str:
    return f'iifname "{interface}" ip saddr {reseau} tcp dport 631 accept comment "{COMMENTAIRE_CUPS}"'


def cups_ouvrir(interface: str, reseau: str) -> None:
    table = chaine_input()
    if not table:
        meurt("chaîne inet filter input introuvable")
    regle = regle_cups(interface, reseau)
    CUPS_NFT.write_text(f"# secubox-nac-partages (#4218) : cupsd au seul LAN du client. Régénéré.\n"
                        f"add rule inet {table} input {regle}\n")
    vivante = lancer(["nft", "list", "chain", "inet", table, "input"]).stdout or ""
    if f'comment "{COMMENTAIRE_CUPS}"' not in vivante:
        lancer(["nft", "add", "rule", "inet", table, "input", *regle.split()])


def cups_fermer() -> None:
    CUPS_NFT.unlink(missing_ok=True)
    table = chaine_input()
    if not table:
        return
    sortie = lancer(["nft", "-a", "list", "chain", "inet", table, "input"]).stdout or ""
    for ligne in sortie.splitlines():
        m = re.search(r'comment "%s" # handle (\d+)$' % COMMENTAIRE_CUPS, ligne.strip())
        if m:
            lancer(["nft", "delete", "rule", "inet", table, "input", "handle", m.group(1)])


def cmd_file_poser(args: list[str]) -> int:
    interface = None
    if "--lan" in args:
        i = args.index("--lan")
        interface = args[i + 1] if i + 1 < len(args) else ""
        args = args[:i] + args[i + 2:]
    if len(args) != 3:
        meurt("usage : file-poser <nom> <ip-maillée-de-la-source> <port-relais> [--lan <interface>]")
    nom, source, port = args
    if not P.NOM_RE.match(nom):
        meurt(f"nom invalide « {nom} »")
    try:
        ip = ipaddress.IPv4Address(source)
    except ValueError:
        meurt(f"IP de la source invalide « {source} »")
    if ip not in P.MAILLAGE or not any(ip in n for n in reseaux_wg()):
        meurt(f"{source} n'est pas joignable par wg-mesh sur ce nœud")
    if not port.isdigit() or not P.PORT_RELAIS_MIN <= int(port) <= P.PORT_RELAIS_MAX:
        meurt(f"port relais invalide « {port} » ({P.PORT_RELAIS_MIN}-{P.PORT_RELAIS_MAX})")
    if not shutil.which("lpadmin") or not shutil.which("cupsctl"):
        meurt(f"CUPS absent : installer d'abord « apt-get install {PAQUETS_PAIR} », puis relancer")
    interface, reseau = lan_de(interface)
    uri = f"ipp://{ip}:{int(port)}{CHEMIN_IPP}"
    r = lancer(["lpadmin", "-p", nom, "-E", "-v", uri, "-m", "everywhere", "-o", "printer-is-shared=true"])
    if r.returncode != 0:
        meurt(f"lpadmin a refusé ({(r.stderr or '').strip()}) — la source a-t-elle ouvert le partage ?")
    # Partage aux seuls clients locaux (Allow @LOCAL) ; jamais d'administration ni d'accès distants.
    lancer(["cupsctl", "--share-printers", "--no-remote-admin", "--no-remote-any"])
    cups_ouvrir(interface, reseau)
    files = [f for f in _lire_json(FILES, []) if isinstance(f, str) and f != nom] + [nom]
    _ecrire_json(FILES, files)
    audit("nac_file_partagee_posee", nom=nom, uri=uri, lan=reseau)
    print(f"[nac-partages] file « {nom} » -> {uri}, partagée à {reseau} ({interface})")
    return 0


def cmd_file_retirer(args: list[str]) -> int:
    if len(args) != 1 or not P.NOM_RE.match(args[0]):
        meurt("usage : file-retirer <nom>")
    nom = args[0]
    if shutil.which("lpadmin"):
        lancer(["lpadmin", "-x", nom])
    files = [f for f in _lire_json(FILES, []) if isinstance(f, str) and f != nom]
    _ecrire_json(FILES, files)
    if not files:
        cups_fermer()
        if shutil.which("cupsctl"):
            lancer(["cupsctl", "--no-share-printers"])
    audit("nac_file_partagee_retiree", nom=nom)
    print(f"[nac-partages] file « {nom} » retirée" + ("" if files else " ; 631 refermé, partage CUPS arrêté"))
    return 0


def main(argv: list[str]) -> int:
    if os.getuid() != 0 and not ESSAI:
        meurt("à lancer en root")
    cmd, args = (argv[0] if argv else ""), argv[1:]
    if cmd == "appliquer":
        return cmd_appliquer()
    if cmd == "etat":
        return cmd_etat()
    if cmd == "partage-poser":
        return cmd_partage_poser(args)
    if cmd == "renvoi-poser":
        return cmd_renvoi_poser(args)
    if cmd == "retirer":
        return cmd_retirer(args)
    if cmd == "file-poser":
        return cmd_file_poser(args)
    if cmd == "file-retirer":
        return cmd_file_retirer(args)
    print(__doc__)
    return 2


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