#!/usr/bin/env python3
# -*- coding: utf-8; -*-
# SPDX-FileCopyrightText: 2025-2026 Medulla, http://www.medulla-tech.io
# SPDX-License-Identifier: GPL-3.0-or-later
"""
medulla_remove_relay - V1.0
Remove a relay (ARS or DMZ ARS) from a Medulla installation.
Supprime un relais (ARS ou ARS DMZ) d'une installation Medulla.

Run as root on the Medulla main server, in the directory used by
install_from_ansible.py. Undoes what playbook 5.6.6 (medullarelay /
medullarelay_dmz) sets up on the main server:

  - relay services stopped over SSH (otherwise the relay re-registers)
  - DMZ: ejabberd node removed from the cluster
  - syncthing / syncthing-depl: relay device removed
  - Apache: syncthing-<relay>.conf and guacamole-<domain>.conf removed
  - /etc/hosts: relay line removed
  - authorized_keys (root and file-transfer): relay key removed
  - xmppmaster / pkgs databases: relay records removed
  - DMZ: MariaDB accounts created for the relay removed
  - ansible_hosts.yml: relay removed
  - DMZ: assessor substitute recreated on the central server (from xmppmaster.ini.local)

Every modified file is first copied to <file dir>/backup/<file>.bak.YYYYMMDD_HHMMSS.
Deleted database rows are saved as JSON in ~/backup/, with a log of the run.

Modes:
  (default)   interactive: relay menu, confirmation, then validation of each step
  --dry-run   shows the plan with details, changes nothing
  --verbose   shows commands, SQL queries and details
  --yes       no question (all steps run)
  --lang      fr / en (default: $LANG)
"""
import argparse
import configparser
import json
import os
import re
import shutil
import socket
import subprocess
import sys
import urllib.request
import xml.etree.ElementTree as ET
from datetime import datetime
from pathlib import Path

import yaml

INVENTORY_FILE = Path.home() / "ansible_hosts.yml"
XMPPMASTER_INI = Path("/etc/mmc/plugins/xmppmaster.ini.local")
ROOT_MYCNF = Path("/root/.my.cnf")
ETC_HOSTS = Path("/etc/hosts")
APACHE_CONF_DIR = Path("/etc/apache2/conf-available")
AUTHORIZED_KEYS = [Path("/root/.ssh/authorized_keys"),
                   Path("/var/lib/pulse2/file-transfer/.ssh/authorized_keys")]
SYNCTHING_INSTANCES = [  # (config.xml, REST port)
    (Path("/var/lib/syncthing/.config/syncthing/config.xml"), 8384),
    (Path("/var/lib/syncthing-depl/.config/syncthing/config.xml"), 8385),
]
RELAY_SSH_USER = "medulla"
RELAY_SSH_KEY = Path("/root/.ssh/id_rsa")
MAIN_RELAY_JID_PREFIX = "rspulse@pulse/"
RELAY_SERVICES = ["pulse-xmpp-agent-relay", "pulse-package-watching"]
DMZ_EXTRA_SERVICES = ["pulse-xmpp-master-substitute-assessor"]
TIMESTAMP = datetime.now().strftime("%Y%m%d_%H%M%S")
VERSION = "1.0"
SUBST_DIR = Path("/etc/pulse-xmpp-agent-substitute")
ASSESSOR_SERVICE = "pulse-xmpp-master-substitute-assessor"
ASSESSOR_UNIT = Path(f"/usr/lib/systemd/system/{ASSESSOR_SERVICE}.service")

# =====================================================
# Translations
# =====================================================
MESSAGES = {
    "not_root": {"fr": "Ce script doit être lancé en root.", "en": "This script must be run as root."},
    "inv_missing": {"fr": "Inventaire introuvable : {p}", "en": "Inventory not found: {p}"},
    "inv_invalid": {"fr": "Inventaire invalide : {p}", "en": "Invalid inventory: {p}"},
    "db_unavailable": {"fr": "Base de données inaccessible ({e}) : les étapes base seront ignorées",
                       "en": "Database unavailable ({e}): database steps will be skipped"},
    "no_relay": {"fr": "Aucun relais trouvé (ni dans l'inventaire, ni en base).",
                 "en": "No relay found (neither in inventory nor in database)."},
    "menu_title": {"fr": "Relais disponibles :", "en": "Available relays:"},
    "menu_inv_db": {"fr": "inventaire + base", "en": "inventory + database"},
    "menu_inv": {"fr": "inventaire seulement", "en": "inventory only"},
    "menu_db": {"fr": "base seulement", "en": "database only"},
    "menu_ask": {"fr": "Numéro du relais à supprimer (q pour quitter) : ",
                 "en": "Number of the relay to remove (q to quit): "},
    "menu_bad": {"fr": "Choix invalide.", "en": "Invalid choice."},
    "non_tty": {"fr": "Pas de terminal interactif : utilisez --ars-fqdn.",
                "en": "No interactive terminal: use --ars-fqdn."},
    "fqdn_unknown": {"fr": "{f} n'est ni dans l'inventaire ni en base.", "en": "{f} is neither in inventory nor in database."},
    "main_refused": {"fr": "{f} est le serveur central : refusé.", "en": "{f} is the main server: refused."},
    "summary": {"fr": "Relais sélectionné", "en": "Selected relay"},
    "discovering": {"fr": "Analyse en cours…", "en": "Analysing…"},
    "plan_title": {"fr": "Actions prévues :", "en": "Planned actions:"},
    "plan_empty": {"fr": "Rien à faire.", "en": "Nothing to do."},
    "notes_title": {"fr": "À vérifier manuellement :", "en": "To check manually:"},
    "confirm": {"fr": "Tapez le nom court du relais ({s}) pour confirmer : ",
                "en": "Type the relay short name ({s}) to confirm: "},
    "aborted": {"fr": "Abandon, aucune modification.", "en": "Aborted, nothing changed."},
    "dry_run": {"fr": "Mode --dry-run : aucune modification.", "en": "--dry-run mode: nothing changed."},
    "ok": {"fr": "OK", "en": "OK"},
    "failed": {"fr": "ÉCHEC", "en": "FAILED"},
    "done": {"fr": "Relais {f} supprimé.", "en": "Relay {f} removed."},
    "done_errors": {"fr": "Terminé avec {n} erreur(s) : voir ci-dessus.", "en": "Finished with {n} error(s): see above."},
    "backup": {"fr": "  sauvegarde : {p}", "en": "  backup: {p}"},
    # discovery
    "ssh_ok": {"fr": "Relais joignable en SSH", "en": "Relay reachable over SSH"},
    "ssh_ko": {"fr": "Relais injoignable en SSH : ses services ne pourront pas être arrêtés. S'il est encore allumé, "
                     "il se réenregistrera auprès du serveur central.",
               "en": "Relay unreachable over SSH: its services cannot be stopped. If it is still running, "
                     "it will register again with the main server."},
    # actions
    "a_stop": {"fr": "Arrêter et désactiver sur le relais : {s}", "en": "Stop and disable on the relay: {s}"},
    "a_ejabberd": {"fr": "Retirer le nœud ejabberd {n} du cluster", "en": "Remove ejabberd node {n} from the cluster"},
    "a_syncthing": {"fr": "Retirer l'appareil {d} ({i}) de {c}", "en": "Remove device {d} ({i}) from {c}"},
    "a_apache": {"fr": "Désactiver et supprimer {p}", "en": "Disable and remove {p}"},
    "a_apache_reload": {"fr": "Recharger Apache", "en": "Reload Apache"},
    "a_hosts": {"fr": "Retirer de {p} : {l}", "en": "Remove from {p}: {l}"},
    "a_keys": {"fr": "Retirer la clé SSH du relais de {p}", "en": "Remove relay SSH key from {p}"},
    "a_db": {"fr": "Supprimer en base le relais id={i} ({j}) et ses dépendances",
             "en": "Delete relay id={i} ({j}) and its dependencies from the database"},
    "a_db_machine": {"fr": "Supprimer l'agent relais de xmppmaster.machines (id={i})",
                     "en": "Delete relay agent from xmppmaster.machines (id={i})"},
    "a_db_cluster": {"fr": "Supprimer le cluster vide '{n}' (id={i})", "en": "Delete empty cluster '{n}' (id={i})"},
    "a_grant": {"fr": "Supprimer le compte MariaDB '{u}'@'{h}'", "en": "Drop MariaDB account '{u}'@'{h}'"},
    "a_inventory": {"fr": "Mettre à jour {p} : {c}", "en": "Update {p}: {c}"},
    # notes
    "n_clients": {"fr": "{n} poste(s) client(s) rattaché(s) à ce relais : ils basculeront sur un autre relais à leur "
                        "prochaine reconfiguration (vérifiez les règles de relais).",
                  "en": "{n} client machine(s) attached to this relay: they will switch to another relay on their next "
                        "reconfiguration (check the relay rules)."},
    "n_share": {"fr": "Partage de paquets '{n}' (pkgs_shares id={i}) créé par ce relais, {p} paquet(s) dedans : "
                      "conservé, à supprimer depuis la console si plus utilisé.",
                "en": "Package share '{n}' (pkgs_shares id={i}) created by this relay, {p} package(s) in it: "
                      "kept, remove it from the console if no longer used."},
    "n_imaging": {"fr": "Serveur d'imagerie '{n}' (imaging.ImagingServer id={i}) lié à ce relais : conservé, "
                        "à dissocier depuis la console.",
                  "en": "Imaging server '{n}' (imaging.ImagingServer id={i}) linked to this relay: kept, "
                        "unassociate it from the console."},
    "n_cluster": {"fr": "Le cluster '{n}' (id={i}) n'aura plus de relais (--delete-empty-clusters pour le supprimer).",
                  "en": "Cluster '{n}' (id={i}) will have no relay left (--delete-empty-clusters to delete it)."},
    "n_dmz_assessor": {"fr": "DMZ : l'ajout du relais DMZ avait désactivé le substitut 'assessor' du serveur central. "
                             "Impossible de le recréer automatiquement : {p}",
                       "en": "DMZ: adding the DMZ relay disabled the 'assessor' substitute on the central server. "
                             "It cannot be recreated automatically: {p}"},
    "n_assessor_check": {"fr": "Vérifiez ensuite : systemctl status pulse-xmpp-master-substitute-assessor",
                         "en": "Then check: systemctl status pulse-xmpp-master-substitute-assessor"},
    "a_assessor": {"fr": "Recréer le substitut assessor sur le serveur central (configuration, service, base)",
                   "en": "Recreate the assessor substitute on the central server (configuration, service, database)"},
    "n_assessor_active": {"fr": "Le substitut assessor est déjà actif sur le serveur central : rien à recréer.",
                          "en": "The assessor substitute is already active on the central server: nothing to recreate."},
    "n_pki": {"fr": "Le certificat du relais émis par la PKI du serveur central n'est pas révoqué.",
              "en": "The relay certificate issued by the main server PKI is not revoked."},
    "n_mmccluster": {"fr": "Serveurs console secondaires (mmccluster) : /etc/hosts non traité, à nettoyer à la main.",
                     "en": "Secondary console servers (mmccluster): /etc/hosts not handled, clean it manually."},
    "step_ask": {"fr": "  Exécuter cette étape ? [O]ui / [n]on, passer / [t]out le reste / [q]uitter : ",
                 "en": "  Run this step? [Y]es / [n]o, skip / [a]ll remaining / [q]uit: "},
    "step_skipped": {"fr": "  ignorée", "en": "  skipped"},
    "step_quit": {"fr": "Arrêt demandé : les étapes restantes ne sont pas exécutées.",
                  "en": "Stopped: remaining steps are not run."},
    "skipped_summary": {"fr": "{n} étape(s) ignorée(s) : {l}", "en": "{n} step(s) skipped: {l}"},
    "skip_stop_warn": {"fr": "Le relais n'a pas été arrêté : s'il tourne encore, il se réenregistrera en base.",
                       "en": "The relay was not stopped: if it is still running, it will register again in the database."},
    "continue_ask": {"fr": "  Continuer malgré l'erreur ? [o/N] : ", "en": "  Continue despite the error? [y/N]: "},
    "log_file": {"fr": "Journal : {p}", "en": "Log: {p}"},
    "n_dbonly": {"fr": "Relais présent en base seulement (FQDN inconnu) : seules les étapes base sont possibles.",
                 "en": "Relay only in database (FQDN unknown): only database steps are possible."},
}

LANG = "fr"


def t(key, **kw):
    msg = MESSAGES[key].get(LANG) or MESSAGES[key]["en"]
    return msg.format(**kw)


def detect_lang():
    for var in ("LC_ALL", "LC_MESSAGES", "LANG"):
        val = os.environ.get(var, "")
        if val:
            return "fr" if val.lower().startswith("fr") else "en"
    return "fr"


VERBOSE = False
LOG_LINES = []


def _color(code, msg):
    return f"\033[{code}m{msg}\033[0m" if sys.stdout.isatty() else msg


def info(msg=""):
    LOG_LINES.append(msg)
    print(msg)


def warn(msg):
    LOG_LINES.append(f"/!\\ {msg}")
    print(_color("33", f"/!\\ {msg}"))


def error(msg):
    LOG_LINES.append(f"[x] {msg}")
    print(_color("31", f"[x] {msg}"), file=sys.stderr)


def vlog(msg):
    """Verbose output: commands, SQL, details."""
    LOG_LINES.append(f"    · {msg}")
    if VERBOSE:
        print(_color("2", f"    · {msg}"))


def ask(prompt):
    ans = input(prompt)
    LOG_LINES.append(f"{prompt}{ans}")
    return ans.strip().lower()


# =====================================================
# Backups
# =====================================================
def backup_file(path: Path) -> Path:
    """Copy path to <dir>/backup/<name>.bak.YYYYMMDD_HHMMSS."""
    bdir = path.parent / "backup"
    bdir.mkdir(mode=0o700, exist_ok=True)
    dest = bdir / f"{path.name}.bak.{TIMESTAMP}"
    shutil.copy2(path, dest)
    info(t("backup", p=dest))
    return dest


def backup_json(name: str, data) -> Path:
    bdir = Path.home() / "backup"
    bdir.mkdir(mode=0o700, exist_ok=True)
    dest = bdir / f"{name}.json.bak.{TIMESTAMP}"
    dest.write_text(json.dumps(data, indent=2, default=str, ensure_ascii=False))
    os.chmod(dest, 0o600)
    info(t("backup", p=dest))
    return dest


# =====================================================
# YAML with vault values kept verbatim
# =====================================================
class VaultValue(str):
    pass


class InventoryLoader(yaml.SafeLoader):
    pass


class InventoryDumper(yaml.SafeDumper):
    pass


InventoryLoader.add_constructor("!vault", lambda loader, node: VaultValue(loader.construct_scalar(node)))
InventoryDumper.add_representer(VaultValue, lambda dumper, data: dumper.represent_scalar("!vault", str(data), style="|"))


def load_inventory(path: Path) -> dict:
    with path.open() as f:
        data = yaml.load(f, Loader=InventoryLoader)
    if not isinstance(data, dict):
        sys.exit(t("inv_invalid", p=path))
    return data


def dump_inventory(inventory: dict) -> str:
    return yaml.dump(inventory, Dumper=InventoryDumper, default_flow_style=False,
                     sort_keys=False, allow_unicode=True, width=1000)


# =====================================================
# Helpers
# =====================================================
def run(cmd, timeout=60):
    vlog("$ " + " ".join(cmd))
    try:
        r = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout)
    except (FileNotFoundError, subprocess.TimeoutExpired) as e:
        r = subprocess.CompletedProcess(cmd, 127, "", str(e))
    vlog(f"rc={r.returncode}" + (f" stderr={r.stderr.strip()[:300]}" if r.stderr.strip() else ""))
    return r


def ssh(fqdn, remote_cmd, timeout=30):
    return run(["ssh", "-o", "BatchMode=yes", "-o", "StrictHostKeyChecking=no", "-o", "ConnectTimeout=10",
                "-i", str(RELAY_SSH_KEY), f"{RELAY_SSH_USER}@{fqdn}", remote_cmd], timeout=timeout)


def resolve_ips(name):
    try:
        return {ai[4][0] for ai in socket.getaddrinfo(name, None, socket.AF_INET)}
    except (socket.gaierror, UnicodeError):
        return set()


class Relay:
    def __init__(self, fqdn=None, group=None, hostvars=None, db_row=None):
        self.fqdn = fqdn
        self.group = group          # 'ars', 'dmzars', '?' or None (database only)
        self.hostvars = hostvars or {}
        self.db_row = db_row
        if fqdn:
            self.short = fqdn.split(".")[0]
            self.domain = str(self.hostvars.get("XMPP_DOMAIN") or self.short)
            self.index = str(self.hostvars.get("RELAY_INDEX") or "")
            self.jid_prefix = f"rs{self.domain}{self.index}@{self.domain}/"
        else:
            m = re.match(r"^rs(.*?)@([^/]+)/", db_row["jid"])
            self.domain = m.group(2) if m else ""
            self.jid_prefix = db_row["jid"].split("/")[0] + "/"
            self.short = self.domain if self.domain != "pulse" else db_row["nameserver"]
            self.index = ""

    @property
    def is_dmz(self):
        return self.group == "dmzars" or self.domain == "pulse"

    @property
    def public_ip(self):
        return self.hostvars.get("PUBLIC_IP")

    def label(self):
        kind = "DMZ" if self.is_dmz else "ARS"
        name = self.fqdn or f"{self.short} ({self.db_row['ipserver']})"
        return f"{name} [{kind}] jid={self.jid_prefix}*"


# =====================================================
# Database
# =====================================================
def db_connect(admin=False):
    import pymysql
    cfg = configparser.ConfigParser(interpolation=None)
    cfg.read(XMPPMASTER_INI)
    host = cfg.get("database", "dbhost", fallback="localhost")
    port = cfg.getint("database", "dbport", fallback=3306)
    kwargs = dict(host=host, port=port, cursorclass=pymysql.cursors.DictCursor, autocommit=False)
    if admin and ROOT_MYCNF.exists():
        kwargs["read_default_file"] = str(ROOT_MYCNF)
    else:
        kwargs.update(user=cfg.get("database", "dbuser", fallback="mmc"),
                      password=cfg.get("database", "dbpasswd", fallback=""), database="xmppmaster")
    return pymysql.connect(**kwargs)


def query(conn, sql, params=None):
    with conn.cursor() as cur:
        cur.execute(sql, params or ())
        vlog(f"SQL {cur._executed if hasattr(cur, '_executed') else sql} -> {cur.rowcount} row(s)")
        return cur.fetchall()


def execute(cur, sql, params=None):
    cur.execute(sql, params or ())
    vlog(f"SQL {getattr(cur, '_executed', sql)} -> {cur.rowcount} row(s)")
    return cur.rowcount


# =====================================================
# Relay list / selection
# =====================================================
def list_relays(inventory, conn):
    relays = []
    medulla_hosts = (inventory.get("medulla") or {}).get("hosts") or {}
    seen = set()
    for group in ("ars", "dmzars"):
        for host in ((inventory.get(group) or {}).get("hosts") or {}):
            relays.append(Relay(host, group, medulla_hosts.get(host) or {}))
            seen.add(host)
    # Hosts in medulla.hosts but dropped from the ars group (--add-ars overwrites the ars group)
    for host, hv in medulla_hosts.items():
        if isinstance(hv, dict) and "PULSEMAIN_FQDN" in hv and host not in seen:
            relays.append(Relay(host, "?", hv))
    db_rows = []
    if conn:
        db_rows = query(conn, "SELECT id, jid, nameserver, ipserver, enabled FROM relayserver WHERE jid NOT LIKE %s",
                        (MAIN_RELAY_JID_PREFIX + "%",))
    for r in relays:
        r.db_rows = [row for row in db_rows if row["jid"].startswith(r.jid_prefix)]
    matched = {row["id"] for r in relays for row in r.db_rows}
    for row in db_rows:
        if row["id"] not in matched:
            r = Relay(db_row=row)
            r.db_rows = [row]
            relays.append(r)
    return relays


def choose_relay(relays):
    if not sys.stdin.isatty():
        sys.exit(t("non_tty"))
    print("\n" + t("menu_title"))
    for i, r in enumerate(relays, 1):
        src = t("menu_db") if not r.fqdn else (t("menu_inv_db") if r.db_rows else t("menu_inv"))
        print(f"  {i:>2}) {r.label()}  — {src}")
    while True:
        ans = ask("\n" + t("menu_ask"))
        if ans in ("q", "quit", "quitter"):
            sys.exit(0)
        if ans.isdigit() and 1 <= int(ans) <= len(relays):
            return relays[int(ans) - 1]
        print(t("menu_bad"))


# =====================================================
# Discovery: build the action plan
# =====================================================
class Plan:
    def __init__(self):
        self.actions = []   # (description, callable, details, key)
        self.notes = []

    def add(self, desc, func, details=None, key=None):
        self.actions.append((desc, func, details or [], key))


def plan_remote(plan, relay, ctx):
    if not relay.fqdn or ctx["args"].no_remote:
        return
    r = ssh(relay.fqdn, "echo SSH_OK")
    if r.returncode == 0 and "SSH_OK" in r.stdout:
        info(f"  {t('ssh_ok')}")
        services = RELAY_SERVICES + (DMZ_EXTRA_SERVICES if relay.is_dmz else [])

        def do():
            res = ssh(relay.fqdn, "sudo -n systemctl disable --now " + " ".join(services))
            if res.returncode != 0:
                raise RuntimeError(res.stderr.strip())
        plan.add(t("a_stop", s=", ".join(services)), do, key="stop",
                 details=[f"ssh {RELAY_SSH_USER}@{relay.fqdn} sudo -n systemctl disable --now " + " ".join(services)])
        if not ctx.get("ssh_key"):
            k = ssh(relay.fqdn, "sudo -n cat /root/.ssh/id_rsa.pub")
            if k.returncode == 0 and k.stdout.startswith("ssh-"):
                ctx["ssh_key"] = k.stdout.strip()
    else:
        warn(t("ssh_ko"))


def plan_ejabberd(plan, relay):
    if not relay.is_dmz or not shutil.which("ejabberdctl"):
        return
    r = run(["ejabberdctl", "list_cluster"])
    for node in r.stdout.split():
        node = node.strip("'")
        host = node.split("@")[-1]
        if relay.short and (host == relay.short or host == relay.fqdn or host.startswith(relay.short + ".")):
            def do(n=node):
                res = run(["ejabberdctl", "leave_cluster", n], timeout=180)
                if res.returncode != 0:
                    raise RuntimeError((res.stdout + res.stderr).strip())
            plan.add(t("a_ejabberd", n=node), do, details=[f"ejabberdctl leave_cluster {node}"])


def plan_syncthing(plan, relay):
    for conf, port in SYNCTHING_INSTANCES:
        if not conf.exists():
            continue
        try:
            root = ET.parse(conf).getroot()
        except ET.ParseError:
            continue
        apikey = root.findtext("gui/apikey")
        for dev in root.findall("device"):
            if dev.get("name") == relay.short:
                dev_id = dev.get("id")

                def do(c=conf, p=port, d=dev_id, k=apikey):
                    backup_file(c)
                    req = urllib.request.Request(f"http://localhost:{p}/rest/config/devices/{d}",
                                                 method="DELETE", headers={"X-API-Key": k})
                    opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
                    with opener.open(req, timeout=30) as resp:
                        if resp.status != 200:
                            raise RuntimeError(f"HTTP {resp.status}")
                plan.add(t("a_syncthing", d=relay.short, i=dev_id[:7], c=conf.parent.parent.parent.name), do,
                         details=[f"DELETE http://localhost:{port}/rest/config/devices/{dev_id}", f"config: {conf}"])


def plan_apache(plan, relay):
    if not APACHE_CONF_DIR.exists():
        return
    names = {f"syncthing-{relay.short}.conf", f"guacamole-{relay.domain}.conf"}
    markers = [m for m in (relay.fqdn, relay.short) if m]
    found = []
    for name in sorted(names):
        p = APACHE_CONF_DIR / name
        if not p.exists():
            continue
        content = p.read_text(errors="replace")
        # guacamole-pulse.conf exists for the DMZ relay only if it points to it
        if not any(m in content for m in markers):
            continue
        found.append(p)

        def do(path=p):
            backup_file(path)
            run(["a2disconf", "-q", path.stem])
            path.unlink()
        plan.add(t("a_apache", p=p), do, details=[f"a2disconf {p.stem}", f"rm {p}"])
    if found:
        def reload():
            test = run(["apache2ctl", "configtest"])
            if test.returncode != 0:
                raise RuntimeError(test.stderr.strip())
            res = run(["systemctl", "reload", "apache2"])
            if res.returncode != 0:
                raise RuntimeError(res.stderr.strip())
        plan.add(t("a_apache_reload"), reload, details=["apache2ctl configtest", "systemctl reload apache2"])


def plan_hosts(plan, relay):
    if not relay.fqdn or not ETC_HOSTS.exists():
        return
    lines = ETC_HOSTS.read_text().splitlines(keepends=True)
    to_remove = [ln for ln in lines if not ln.lstrip().startswith("#") and relay.fqdn in ln.split()[1:]]
    if not to_remove:
        return

    def do():
        backup_file(ETC_HOSTS)
        current = ETC_HOSTS.read_text().splitlines(keepends=True)
        ETC_HOSTS.write_text("".join(ln for ln in current if ln not in to_remove))
    plan.add(t("a_hosts", p=ETC_HOSTS, l=" | ".join(ln.strip() for ln in to_remove)), do,
             details=[f"- {ln.strip()}" for ln in to_remove])


def plan_keys(plan, ctx):
    key = ctx.get("ssh_key")
    if not key or len(key.split()) < 2:
        return
    blob = key.split()[1]
    for path in AUTHORIZED_KEYS:
        if not path.exists() or blob not in path.read_text():
            continue

        def do(p=path):
            backup_file(p)
            st = p.stat()
            p.write_text("".join(ln for ln in p.read_text().splitlines(keepends=True) if blob not in ln))
            os.chown(p, st.st_uid, st.st_gid)
            os.chmod(p, st.st_mode)
        plan.add(t("a_keys", p=path), do, details=[f"- {key.split()[0]} {blob[:20]}…{blob[-12:]} {' '.join(key.split()[2:])}"])


def plan_database(plan, relay, conn, ctx):
    if not conn:
        return
    if relay.jid_prefix == MAIN_RELAY_JID_PREFIX:
        sys.exit(t("main_refused", f=relay.jid_prefix))
    rows = query(conn, "SELECT * FROM relayserver WHERE jid LIKE %s", (relay.jid_prefix + "%",))
    machines = query(conn, "SELECT id, hostname, jid FROM machines WHERE agenttype = 'relayserver' AND jid LIKE %s",
                     (relay.jid_prefix + "%",))
    ids = [r["id"] for r in rows]
    for r in rows:
        if r.get("ssh_public_key") and not ctx.get("ssh_key"):
            ctx["ssh_key"] = r["ssh_public_key"].strip()

    if ids:
        ph = ",".join(["%s"] * len(ids))
        # Clients still attached
        n = query(conn, "SELECT COUNT(*) AS n FROM machines WHERE agenttype = 'machine' AND groupdeploy LIKE %s",
                  (relay.jid_prefix + "%",))[0]["n"]
        if n:
            plan.notes.append(t("n_clients", n=n))
        # Package shares created by this relay (kept)
        for s in query(conn, f"SELECT id, name FROM pkgs.pkgs_shares WHERE ars_id IN ({ph})", ids):
            p = query(conn, "SELECT COUNT(*) AS n FROM pkgs.packages WHERE pkgs_share_id = %s", (s["id"],))[0]["n"]
            plan.notes.append(t("n_share", n=s["name"], i=s["id"], p=p))
        # Clusters left empty
        clusters = query(conn, f"SELECT DISTINCT c.id, c.name FROM cluster_ars c JOIN has_cluster_ars h "
                               f"ON h.id_cluster = c.id WHERE h.id_ars IN ({ph})", ids)
        empty = []
        for c in clusters:
            others = query(conn, f"SELECT COUNT(*) AS n FROM has_cluster_ars WHERE id_cluster = %s "
                                 f"AND id_ars NOT IN ({ph})", [c["id"]] + ids)[0]["n"]
            if not others:
                empty.append(c)
        # Rows saved before deletion
        saved = {"relayserver": rows, "machines": machines}
        for table, col in (("xmppmaster.has_relayserverrules", "relayserver_id"),
                           ("xmppmaster.has_cluster_ars", "id_ars"),
                           ("xmppmaster.substituteconf", "relayserver_id"),
                           ("pkgs.pkgs_shares_ars", "id")):
            saved[table] = query(conn, f"SELECT * FROM {table} WHERE {col} IN ({ph})", ids)

        def do():
            backup_json(f"relay_{relay.short}_db", saved)
            with conn.cursor() as cur:
                for sql in (
                    f"DELETE FROM xmppmaster.has_relayserverrules WHERE relayserver_id IN ({ph})",
                    f"DELETE FROM xmppmaster.has_cluster_ars WHERE id_ars IN ({ph})",
                    f"DELETE FROM xmppmaster.substituteconf WHERE relayserver_id IN ({ph})",
                    f"DELETE FROM pkgs.pkgs_shares_ars_web WHERE ars_share_id IN ({ph})",
                    f"DELETE FROM pkgs.pkgs_shares_ars WHERE id IN ({ph})",
                    f"DELETE FROM xmppmaster.relayserver WHERE id IN ({ph})",
                ):
                    execute(cur, sql, ids)
            conn.commit()
        plan.add(t("a_db", i=",".join(map(str, ids)), j=", ".join(r["jid"] for r in rows)), do,
                 details=[f"{tbl}: {len(v)} row(s)" for tbl, v in saved.items() if tbl != "machines"]
                 + ["pkgs.pkgs_shares_ars_web: ars_share_id IN (" + ",".join(map(str, ids)) + ")"])

        for c in empty:
            if ctx["args"].delete_empty_clusters:
                def do_cluster(cid=c["id"]):
                    with conn.cursor() as cur:
                        execute(cur, "DELETE FROM pkgs.pkgs_rules_global WHERE pkgs_cluster_ars_id = %s", (cid,))
                        execute(cur, "DELETE FROM xmppmaster.cluster_ars WHERE id = %s", (cid,))
                    conn.commit()
                plan.add(t("a_db_cluster", n=c["name"], i=c["id"]), do_cluster,
                         details=["pkgs.pkgs_rules_global, xmppmaster.cluster_ars"])
            else:
                plan.notes.append(t("n_cluster", n=c["name"], i=c["id"]))

    if machines:
        mids = [m["id"] for m in machines]

        def do_machines():
            with conn.cursor() as cur:
                execute(cur, "DELETE FROM xmppmaster.machines WHERE id IN (" + ",".join(["%s"] * len(mids)) + ")", mids)
            conn.commit()
        plan.add(t("a_db_machine", i=",".join(map(str, mids))), do_machines,
                 details=[f"{m['hostname']} {m['jid']}" for m in machines])

    # Imaging server (kept)
    if relay.fqdn:
        try:
            for s in query(conn, "SELECT id, name FROM imaging.ImagingServer WHERE davos_opts LIKE %s",
                           (f"%fqdn={relay.fqdn} %",)):
                plan.notes.append(t("n_imaging", n=s["name"], i=s["id"]))
        except Exception:
            pass


def plan_grants(plan, relay):
    """DMZ: accounts created on the main DB (ALLOW_FROM_HOSTS + substitute_agent)."""
    if not relay.is_dmz or not relay.fqdn:
        return
    hosts = {relay.fqdn} | resolve_ips(relay.fqdn)
    hosts |= {row["ipserver"] for row in getattr(relay, "db_rows", []) if row.get("ipserver")}
    if relay.public_ip:
        hosts.add(relay.public_ip)
    try:
        conn = db_connect(admin=True)
    except Exception as e:
        warn(t("db_unavailable", e=e))
        return
    ph = ",".join(["%s"] * len(hosts))
    accounts = query(conn, f"SELECT User, Host FROM mysql.user WHERE Host IN ({ph}) AND User IN ('root', 'mmc')",
                     sorted(hosts))
    for a in accounts:
        def do(u=a["User"], h=a["Host"]):
            grants = [list(g.values())[0] for g in query(conn, "SHOW GRANTS FOR %s@%s", (u, h))]
            backup_json(f"relay_{relay.short}_grants_{u}_{h}", grants)
            with conn.cursor() as cur:
                execute(cur, "DROP USER %s@%s", (u, h))
            conn.commit()
        plan.add(t("a_grant", u=a["User"], h=a["Host"]), do, details=[f"DROP USER '{a['User']}'@'{a['Host']}'"])


def remove_from_inventory(inventory, fqdn):
    changes = []
    medulla_hosts = (inventory.get("medulla") or {}).get("hosts") or {}
    relay_vars = medulla_hosts.get(fqdn) or {}
    public_ip = relay_vars.get("PUBLIC_IP") if isinstance(relay_vars, dict) else None
    if fqdn in medulla_hosts:
        del medulla_hosts[fqdn]
        changes.append(f"-medulla.hosts.{fqdn}")
    for group in ("ars", "dmzars"):
        grp = inventory.get(group)
        if not grp:
            continue
        hosts = grp.get("hosts") or {}
        if fqdn in hosts:
            del hosts[fqdn]
            changes.append(f"-{group}.hosts.{fqdn}")
        if not hosts:
            del inventory[group]
            changes.append(f"-{group}")
    mmc_vars = (inventory.get("mmcmain") or {}).get("vars") or {}
    allow = mmc_vars.get("ALLOW_FROM_HOSTS")
    if isinstance(allow, list):
        kept = [h for h in allow if h not in (fqdn, public_ip)]
        if kept != allow:
            if kept:
                mmc_vars["ALLOW_FROM_HOSTS"] = kept
            else:
                del mmc_vars["ALLOW_FROM_HOSTS"]
            changes.append("ALLOW_FROM_HOSTS")
    # Main IP alias (ansible_connection: local) only useful while a relay exists
    if not any(g in inventory for g in ("ars", "dmzars")) and not any(
            isinstance(v, dict) and "PULSEMAIN_FQDN" in v for v in medulla_hosts.values()):
        for host, hv in list(medulla_hosts.items()):
            if hv == {"ansible_connection": "local"} and re.match(r"^\d+\.\d+\.\d+\.\d+$", str(host)):
                del medulla_hosts[host]
                changes.append(f"-medulla.hosts.{host}")
    return changes


def plan_assessor(plan, relay, conn):
    """DMZ: the DMZ playbook stopped the assessor on the central server, deleted its two
    .ini.local files and its substituteconf rows. Rebuild them from xmppmaster.ini.local,
    which holds the same values the substitute_agent Ansible role uses."""
    if not relay.is_dmz or not relay.fqdn:
        return
    if run(["systemctl", "is-active", "--quiet", ASSESSOR_SERVICE]).returncode == 0:
        plan.notes.append(t("n_assessor_active"))
        return
    if not ASSESSOR_UNIT.exists():
        plan.notes.append(t("n_dmz_assessor", p=f"{ASSESSOR_UNIT} absent"))
        return
    cfg = configparser.ConfigParser(interpolation=None)
    cfg.read(XMPPMASTER_INI)

    def g(section, key):
        return cfg.get(section, key, fallback="").strip()
    values = {
        "server": g("connection", "server"), "password": g("connection", "password"),
        "dbhost": g("database", "dbhost") or "localhost", "dbport": g("database", "dbport") or "3306",
        "dbuser": g("database", "dbuser") or "mmc", "dbpasswd": g("database", "dbpasswd"),
        "serverip": g("defaultconnection", "serverip"), "guac": g("defaultconnection", "guacamole_baseurl"),
        "aes": g("defaultconnection", "keyAES32"), "announce": g("syncthing", "announce_server"),
    }
    missing = [k for k in ("server", "password", "dbpasswd", "serverip", "aes") if not values[k]]
    if missing:
        plan.notes.append(t("n_dmz_assessor", p=f"{XMPPMASTER_INI}: " + ", ".join(missing)))
        return
    # XMPP domain of the central server, taken from another substitute (default: pulse)
    domain = "pulse"
    for other in sorted(SUBST_DIR.glob("agent_master_substitute_*.ini.local")):
        o = configparser.ConfigParser(interpolation=None)
        o.read(other)
        jid = o.get("connection", "jidmastersubstitute", fallback="")
        if "@" in jid:
            domain = jid.split("@", 1)[1]
            break
    jid = f"master_asse@{domain}"
    files = {
        SUBST_DIR / "agent_master_substitute_asse.ini.local": (
            "[connection]\n"
            f"server = {values['server']}\n"
            f"password = {values['password']}\n"
            f"jidmastersubstitute = {jid}\n\n"
            "[xmppdatabase]\n"
            f"xmpp_dbhost = {values['dbhost']}\n"
            f"xmpp_dbport = {values['dbport']}\n"
            f"xmpp_dbuser = {values['dbuser']}\n"
            f"xmpp_dbpasswd = {values['dbpasswd']}\n"),
        SUBST_DIR / "assessor_agent.ini.local": (
            "[parameters]\n"
            f"serverip = {values['serverip']}\n"
            f"guacamole_baseurl = {values['guac']}\n"
            f"keyAES32 = {values['aes']}\n"
            f"announce_server = {values['announce']}\n"),
    }

    def do():
        for path, content in files.items():
            if path.exists():
                backup_file(path)
            path.write_text(content)
            os.chmod(path, 0o644)
            vlog(f"written {path}")
        if conn:
            with conn.cursor() as cur:
                execute(cur, "INSERT IGNORE INTO xmppmaster.substituteconf (type, jidsubtitute, relayserver_id) "
                             "SELECT 'assessor', %s, id FROM xmppmaster.relayserver", (jid,))
            conn.commit()
        for cmd in (["systemctl", "daemon-reload"], ["systemctl", "enable", ASSESSOR_SERVICE],
                    ["systemctl", "restart", ASSESSOR_SERVICE]):
            r = run(cmd)
            if r.returncode != 0:
                raise RuntimeError(f"{' '.join(cmd)}: {r.stderr.strip()}")
        if run(["systemctl", "is-active", "--quiet", ASSESSOR_SERVICE]).returncode != 0:
            raise RuntimeError(f"{ASSESSOR_SERVICE} not active (journalctl -u {ASSESSOR_SERVICE})")
    plan.add(t("a_assessor"), do, details=[f"{p} ({XMPPMASTER_INI})" for p in files]
             + [f"xmppmaster.substituteconf: assessor / {jid} for each relay",
                f"systemctl enable + restart {ASSESSOR_SERVICE}"])
    plan.notes.append(t("n_assessor_check"))


def plan_inventory(plan, relay, inventory, inv_path):
    if not relay.fqdn:
        return
    new_inv = yaml.load(dump_inventory(inventory), Loader=InventoryLoader)   # deep copy
    changes = remove_from_inventory(new_inv, relay.fqdn)
    if not changes:
        return

    def do():
        backup_file(inv_path)
        inv_path.write_text(dump_inventory(new_inv))
        if load_inventory(inv_path) != new_inv:
            raise RuntimeError("inventory reload mismatch")
    plan.add(t("a_inventory", p=inv_path, c=", ".join(changes)), do, details=changes)


# =====================================================
# Entry point
# =====================================================
def main():
    global LANG, VERBOSE
    parser = argparse.ArgumentParser(description=f"Remove a Medulla relay / Supprimer un relais Medulla (V{VERSION})")
    parser.add_argument("--ars-fqdn", help="Relay FQDN (otherwise interactive menu) / FQDN du relais (sinon menu)")
    parser.add_argument("--inventory", type=Path, default=INVENTORY_FILE,
                        help=f"Ansible inventory / Inventaire Ansible (default {INVENTORY_FILE})")
    parser.add_argument("--version", action="version", version=f"medulla_remove_relay V{VERSION}")
    parser.add_argument("--lang", choices=["fr", "en"], help="Language / Langue (default: $LANG)")
    parser.add_argument("--dry-run", action="store_true", help="Show the plan only / Affiche le plan uniquement")
    parser.add_argument("--no-remote", action="store_true", help="Do not connect to the relay / Ne pas se connecter au relais")
    parser.add_argument("--delete-empty-clusters", action="store_true",
                        help="Delete clusters left without relay / Supprimer les clusters vides")
    parser.add_argument("-v", "--verbose", action="store_true",
                        help="Show commands, SQL and details / Affiche commandes, SQL et détails")
    parser.add_argument("-y", "--yes", action="store_true",
                        help="No confirmation, no step validation / Sans confirmation ni validation par étape")
    args = parser.parse_args()
    LANG = args.lang or detect_lang()
    VERBOSE = args.verbose

    if os.geteuid() != 0 and not args.dry_run:
        sys.exit(t("not_root"))
    if not args.inventory.exists():
        sys.exit(t("inv_missing", p=args.inventory))
    inventory = load_inventory(args.inventory)

    try:
        conn = db_connect()
    except Exception as e:
        warn(t("db_unavailable", e=e))
        conn = None

    relays = list_relays(inventory, conn)
    if args.ars_fqdn:
        main_hosts = list(((inventory.get("medulla") or {}).get("hosts") or {}).keys())
        if main_hosts and args.ars_fqdn == main_hosts[0]:
            sys.exit(t("main_refused", f=args.ars_fqdn))
        relay = next((r for r in relays if r.fqdn == args.ars_fqdn), None)
        if not relay:
            sys.exit(t("fqdn_unknown", f=args.ars_fqdn))
    else:
        if not relays:
            sys.exit(t("no_relay"))
        relay = choose_relay(relays)

    info(f"\n{t('summary')} : {relay.label()}")
    if not relay.fqdn:
        warn(t("n_dbonly"))
    info(t("discovering"))

    ctx = {"args": args}
    plan = Plan()
    plan_remote(plan, relay, ctx)          # first: stop the agent so it does not re-register
    plan_ejabberd(plan, relay)
    plan_syncthing(plan, relay)
    plan_apache(plan, relay)
    plan_hosts(plan, relay)
    plan_database(plan, relay, conn, ctx)  # also fetches the relay ssh key
    plan_keys(plan, ctx)
    plan_grants(plan, relay)
    plan_inventory(plan, relay, inventory, args.inventory)
    plan_assessor(plan, relay, conn)       # last: the DMZ relay is gone from relayserver
    if relay.fqdn and (inventory.get("mmccluster") or {}).get("hosts"):
        plan.notes.append(t("n_mmccluster"))
    plan.notes.append(t("n_pki"))

    info("\n" + t("plan_title"))
    if not plan.actions:
        info("  " + t("plan_empty"))
    for i, (desc, _, details, _) in enumerate(plan.actions, 1):
        info(f"  {i:>2}. {desc}")
        if VERBOSE or args.dry_run:
            for d in details:
                info(f"        {d}")
    if plan.notes:
        info("\n" + t("notes_title"))
        for n in plan.notes:
            info(f"  - {n}")
    info()

    if args.dry_run:
        info(t("dry_run"))
        return
    if not plan.actions:
        return
    interactive = not args.yes
    if interactive:
        if not sys.stdin.isatty():
            sys.exit(t("non_tty"))
        if ask(t("confirm", s=relay.short)) != relay.short.lower():
            sys.exit(t("aborted"))

    errors, skipped = 0, []
    log_path = Path.home() / "backup" / f"remove_relay_{relay.short}.log.{TIMESTAMP}"
    try:
        for i, (desc, func, details, key) in enumerate(plan.actions, 1):
            info(f"\n[{i}/{len(plan.actions)}] {desc}")
            for d in details:
                info(f"      {d}")
            if interactive:
                ans = ask(t("step_ask"))
                if ans in ("q", "quit", "quitter"):
                    skipped += [str(j) for j in range(i, len(plan.actions) + 1)]
                    warn(t("step_quit"))
                    break
                if ans in ("t", "a", "tout", "all"):
                    interactive = False
                elif ans in ("n", "non", "no"):
                    skipped.append(str(i))
                    info(t("step_skipped"))
                    if key == "stop":
                        warn(t("skip_stop_warn"))
                    continue
            try:
                func()
                info(f"  {t('ok')}")
            except Exception as e:
                errors += 1
                error(f"{t('failed')}: {e}")
                if conn:
                    try:
                        conn.rollback()
                    except Exception:
                        pass
                if interactive and ask(t("continue_ask")) not in ("o", "oui", "y", "yes"):
                    skipped += [str(j) for j in range(i + 1, len(plan.actions) + 1)]
                    warn(t("step_quit"))
                    break
    finally:
        if conn:
            conn.close()
        info()
        if skipped:
            warn(t("skipped_summary", n=len(skipped), l=", ".join(skipped)))
        if errors:
            error(t("done_errors", n=errors))
        elif not skipped:
            info(t("done", f=relay.fqdn or relay.short))
        if plan.notes:
            info("\n" + t("notes_title"))
            for n in plan.notes:
                info(f"  - {n}")
        log_path.parent.mkdir(mode=0o700, exist_ok=True)
        log_path.write_text("\n".join(LOG_LINES) + "\n")
        os.chmod(log_path, 0o600)
        print("\n" + t("log_file", p=log_path))
    if errors:
        sys.exit(1)

if __name__ == "__main__":
    main()
