#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# SPDX-FileCopyrightText: 2024-2026 Medulla, http://www.medulla-tech.io
# SPDX-License-Identifier: GPL-3.0-or-later
#
# File name: medulla_itsm.py
# Replaces: check_itsm_access.sh + change_itsm_parameters.py
"""
Check and configure the connection between Medulla and an external GLPI (ITSM).

Modes
  check : diagnostics only, nothing is modified
  fix   : (re)configure Medulla for an external GLPI, then run every check again

Examples
  ./medulla_itsm.py                                   # interactive (language + mode menus)
  ./medulla_itsm.py --lang fr --mode check
  ./medulla_itsm.py --lang en --mode fix --non-interactive \\
      --url https://glpi.example.com --db-host 10.0.0.5 --db-name glpi --db-user medulla \\
      --api-url https://glpi.example.com/api.php/v1 --api-user medulla-api ...

  Secrets can be passed through environment variables instead of the command line
  (not visible in `ps`): ITSM_DB_PASS, ITSM_API_PASS, ITSM_APP_TOKEN, ITSM_USER_TOKEN,
  ITSM_CRYPT_KEY.

Exit codes : 0 = no failed check, 1 = at least one failed check, 2 = aborted / bad usage,
             3 = check mode: no external GLPI connected yet (dbhost = localhost in glpi.ini.local)
Debian deps: python3-mysql.connector python3-requests (python3-nacl recommended)
"""

import argparse
import base64
import configparser
import copy
import datetime
import getpass
import ipaddress
import os
import re
import shutil
import socket
import subprocess
import sys
import tempfile
import time
from urllib.parse import urlparse

try:
    import mysql.connector
    DBError = mysql.connector.Error
except ImportError:  # reported by the prerequisite check
    mysql = None
    DBError = Exception
try:
    import requests
    import urllib3
    urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
except ImportError:
    requests = None
try:
    from nacl.bindings import crypto_aead_xchacha20poly1305_ietf_decrypt
except ImportError:
    crypto_aead_xchacha20poly1305_ietf_decrypt = None

# ─────────────────────────────────────────────────────────────────────────────
# Constants
# ─────────────────────────────────────────────────────────────────────────────
GLPI_INI = "/etc/mmc/plugins/glpi.ini"
GLPI_INI_LOCAL = GLPI_INI + ".local"
XMPPMASTER_INI = "/etc/mmc/plugins/xmppmaster.ini"
SUBST_DIR = "/etc/pulse-xmpp-agent-substitute"
SUBS_INV_INI = f"{SUBST_DIR}/agent_master_substitute_inv.ini"
SUBS_REG_INI = f"{SUBST_DIR}/agent_master_substitute_reg.ini"
REGAGENT_INI = f"{SUBST_DIR}/registeryagent.ini"
CLIENT_INV_INI = "/var/lib/pulse2/clients/config/inventory.ini"
GEN_OPTIONS = "/var/lib/pulse2/clients/.generation_options"
GEN_AGENT = "/var/lib/pulse2/clients/generate-pulse-agent.sh"
GEN_AGENT_LOG = "/tmp/generate_agent.log"
SERVICES = ("mmc-agent",
            "pulse-xmpp-master-substitute-inventory",
            "pulse-xmpp-master-substitute-registration")

SQL_FILES = {10: "https://dl.medulla-tech.io/nc/glpi-100.sql",
             11: "https://dl.medulla-tech.io/nc/glpi-110.sql"}

REQUIRED_TABLES = ("glpi_computers", "glpi_users", "glpi_profiles", "glpi_entities", "glpi_groups",
                   "glpi_softwares", "glpi_networkports", "glpi_printers", "glpi_monitors",
                   "glpi_peripherals", "glpi_tickets", "glpi_changes", "glpi_problems",
                   "glpi_projects", "glpi_locations", "glpi_plugin_glpiinventory_collects")
REQUIRED_VIEWS = ("glpi_computers_pulse", "glpi_view_computers_items_printer",
                  "glpi_view_computers_items_peripheral", "glpi_view_peripherals_manufacturers")

# Params attribute -> admin.saas_application setting_name
SAAS_KEYS = {"app_token": "glpi_mmc_app_token",
             "user_token": "glpi_root_user_token",
             "api_url": "glpi_url_base_api",
             "crypt_key": "glpi_crypt_key"}
# setting_name -> setting_description, as inserted by Medulla itself
SAAS_DESCRIPTIONS = {"glpi_mmc_app_token": "MMC application token for ITSM API",
                     "glpi_url_base_api": "MMC application URL for ITSM API",
                     "type_api": "ITSM API type",
                     "glpi_root_user_token": "MMC user token for ITSM API super-admin user",
                     "glpi_crypt_key": "GLPI 11 sodium encryption key (base64)"}
SAAS_TYPE_API = "glpi_rest"          # value of type_api when empty
CRYPT_KEY_GLPI10 = "REPLACE"         # glpi_crypt_key when empty on GLPI 10 (the key is only used by GLPI 11)
RESTART_PULSE_SERVICES = "/usr/sbin/restart-pulse-services"

MMC_API_CLIENT = "MMC"   # API client that Medulla must use in GLPI (glpi_apiclients.name)

FEDERATED_SERVER = "itsm_federated"
# local table (xmppmaster) -> (remote GLPI table, columns)
# Medulla >= 5.6.6 (update_medulla.sh, update_565_to_566) adds these columns to local_glpi_machines;
# they are read by xmppmaster schema-113.sql (COALESCE(last_inventory_update, date_mod)).
MACHINES_COLUMNS_SINCE = (5, 6, 6)
MACHINES_EXTRA_COLUMNS = {"last_inventory_update": "`last_inventory_update` timestamp NULL DEFAULT NULL",
                          "last_boot": "`last_boot` timestamp NULL DEFAULT NULL",
                          "date_mod": "`date_mod` timestamp NULL DEFAULT NULL"}
MEDULLA_VERSION_FILE = "/var/lib/mmc/version"


def medulla_version():
    """Installed Medulla version, from the mmc-agent package (same as `apt list --installed | grep mmc`),
    else from /var/lib/mmc/version. Returns (tuple, text) or (None, "")."""
    candidates = []
    res = run(["dpkg-query", "-W", "-f=${Version}", "mmc-agent"], timeout=20)
    if res.returncode == 0:
        candidates.append(res.stdout.strip())
    try:
        with open(MEDULLA_VERSION_FILE) as fh:
            candidates.append(fh.read().strip())
    except OSError:
        pass
    for text in candidates:
        m = re.match(r"(\d+)\.(\d+)\.(\d+)", text)      # "5.6.5git20260924221101.c13dbda1-1" -> 5.6.5
        if m:
            return tuple(int(x) for x in m.groups()), m.group(0)
    return None, ""


def machines_needs_extra_columns():
    version, _ = medulla_version()
    return version is not None and version >= MACHINES_COLUMNS_SINCE


def federated_columns(name):
    """Column definition of a local_glpi_* table for the installed Medulla version."""
    columns = FEDERATED_TABLES[name][1]
    if name == "local_glpi_machines" and machines_needs_extra_columns():
        columns += ", " + ", ".join(MACHINES_EXTRA_COLUMNS.values())
    return columns


FEDERATED_TABLES = {
    "local_glpi_configs": ("glpi_configs",
        "`id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(150) DEFAULT NULL, "
        "`value` text DEFAULT NULL, PRIMARY KEY (`id`)"),
    "local_glpi_machines": ("glpi_computers",
        "`id` int NOT NULL, PRIMARY KEY (`id`), `entities_id` int(10) NOT NULL DEFAULT 0, "
        "`name` varchar(255) NULL DEFAULT NULL, `is_template` tinyint(4) NOT NULL DEFAULT 0, "
        "`is_deleted` tinyint(4) NOT NULL DEFAULT 0"),
    "local_glpi_filters": ("glpi_computers",
        "`id` int NOT NULL, PRIMARY KEY (`id`), `states_id` int(10) NOT NULL DEFAULT 0, "
        "`entities_id` int(10) NOT NULL DEFAULT 0, `computertypes_id` int(10) NOT NULL DEFAULT 0, "
        "`autoupdatesystems_id` int(10) NOT NULL DEFAULT 0"),
    "local_glpi_items_softwareversions": ("glpi_items_softwareversions",
        "`id` int NOT NULL, PRIMARY KEY (`id`), `items_id` int NOT NULL DEFAULT 0, "
        "`itemtype` varchar(100) NOT NULL, `softwareversions_id` int NOT NULL DEFAULT 0"),
    "local_glpi_softwareversions": ("glpi_softwareversions",
        "`id` int NOT NULL, PRIMARY KEY (`id`), `softwares_id` int NOT NULL DEFAULT 0, "
        "`name` varchar(255) DEFAULT NULL, `comment` text DEFAULT NULL"),
    "local_glpi_softwares": ("glpi_softwares",
        "`id` int NOT NULL, PRIMARY KEY (`id`), `name` varchar(255) NULL DEFAULT NULL, "
        "`comment` text NULL DEFAULT NULL"),
    "local_glpi_entities": ("glpi_entities",
        "`id` int(10) unsigned NOT NULL DEFAULT 0, PRIMARY KEY (`id`), "
        "`completename` text DEFAULT NULL, `name` varchar(255) DEFAULT NULL"),
}
TIMEOUT = 10

# ─────────────────────────────────────────────────────────────────────────────
# i18n
# ─────────────────────────────────────────────────────────────────────────────
LANGS = ("en", "fr", "es", "de")
LANG = "en"


def T(key, **kw):
    """Translate a message key (MSG is defined at the end of the file)."""
    entry = MSG.get(key)
    if entry is None:
        txt = key
    else:
        txt = entry[LANGS.index(LANG)] if len(entry) == len(LANGS) else entry[0]
    if kw:
        try:
            return txt.format(**kw)
        except (KeyError, IndexError, ValueError):
            return txt
    return txt


def detect_lang():
    for var in ("LC_ALL", "LC_MESSAGES", "LANG"):
        code = os.environ.get(var, "")[:2].lower()
        if code in LANGS:
            return code
    return "en"


# ─────────────────────────────────────────────────────────────────────────────
# Output helpers
# ─────────────────────────────────────────────────────────────────────────────
COLOR = sys.stdout.isatty() and "NO_COLOR" not in os.environ


def _c(code, s):
    return f"\033[{code}m{s}\033[0m" if COLOR else s


def bold(s): return _c("1", s)
def green(s): return _c("32", s)
def red(s): return _c("31", s)
def yellow(s): return _c("33", s)
def cyan(s): return _c("36", s)
def dim(s): return _c("2", s)


def short(e, n=220):
    """One-line, readable error message (strips the urllib3 retry boilerplate)."""
    s = " ".join(str(e).split())
    if "ConnectionPool" in s:
        m = re.search(r"(\[Errno -?\d+\][^\"')]*)", s)
        if m:
            return m.group(1).strip()[:n]
        m = re.search(r"Caused by (\w+)", s)
        if m:
            return m.group(1)
    return s[:n]


def box(lines):
    width = max(len(line) for line in lines) + 2
    print("  " + yellow("┏" + "━" * width + "┓"))
    for line in lines:
        print("  " + yellow("┃") + " " + line.ljust(width - 1) + yellow("┃"))
    print("  " + yellow("┗" + "━" * width + "┛"))


# How a failure can be fixed (used to preview what fix mode will do):
#   auto   = fixed by the files / database objects that fix mode rewrites
#   params = fixed by re-entering a parameter when fix mode asks for it
#   sql    = fixed by applying glpi-100.sql / glpi-110.sql (fix mode offers to)
#   manual = cannot be fixed by this script (GLPI side, network, Medulla server)
AUTO_FIX_SECTIONS = ("sec_medulla_conf", "sec_federated", "sec_services")
FIX_CATEGORIES = ("auto", "params", "sql", "manual")


class Report:
    """Counts and prints check results."""

    def __init__(self):
        self.passed = self.failed = self.warned = 0
        self.failures, self.warnings = [], []
        self.failure_fixes = []          # parallel to self.failures
        self.section_key = None

    def section(self, title):
        self.section_key = next((k for k in MSG if k.startswith("sec_") and T(k) == title), None)
        print()
        print(bold(f"── {title} " + "─" * max(4, 60 - len(title))))

    def info(self, msg):
        print(f"  {cyan('[=]')} {msg}")

    def ok(self, msg):
        self.passed += 1
        print(f"  {green('[✓]')} {msg}")

    def warn(self, msg, hint=None):
        self.warned += 1
        self.warnings.append(msg)
        print(f"  {yellow('[!]')} {msg}")
        self._hint(hint)

    def fail(self, msg, hint=None, fix=None):
        self.failed += 1
        self.failures.append(msg)
        self.failure_fixes.append(fix or ("auto" if self.section_key in AUTO_FIX_SECTIONS else "manual"))
        print(f"  {red('[✗]')} {msg}")
        self._hint(hint)

    def failures_by_fix(self):
        groups = {cat: [] for cat in FIX_CATEGORIES}
        for msg, cat in zip(self.failures, self.failure_fixes):
            groups[cat].append(msg)
        return groups

    @staticmethod
    def _hint(hint):
        if not hint:
            return
        for line in (hint if isinstance(hint, (list, tuple)) else [hint]):
            print(f"      {dim('→')} {line}")

    def snapshot(self):
        return (self.passed, self.failed, self.warned, len(self.failures), len(self.warnings))

    def restore(self, snap):
        self.passed, self.failed, self.warned = snap[:3]
        del self.failures[snap[3]:]
        del self.failure_fixes[snap[3]:]
        del self.warnings[snap[4]:]

    def summary(self, title=None):
        line = "═" * 64
        print()
        print(bold(line))
        print(bold(f"  {title or T('summary_title')}"))
        print(f"  {green(T('sum_passed', n=self.passed))}   "
              f"{yellow(T('sum_warned', n=self.warned))}   "
              f"{red(T('sum_failed', n=self.failed))}")
        if self.failures:
            print()
            print(bold("  " + T("sum_failures")))
            for f in self.failures:
                print(f"   {red('✗')} {f}")
        if self.warnings:
            print()
            print(bold("  " + T("sum_warnings")))
            for w in self.warnings:
                print(f"   {yellow('!')} {w}")
        print(bold(line))
        print("  " + (green(T("all_good")) if self.failed == 0 else red(T("some_failed"))))
        return 0 if self.failed == 0 else 1


# ─────────────────────────────────────────────────────────────────────────────
# Interactive prompts
# ─────────────────────────────────────────────────────────────────────────────
YES = {"y", "yes", "o", "oui", "s", "si", "sí", "j", "ja"}
NO = {"n", "no", "non", "nein"}


def ask(label, default="", secret=False, required=True, validator=None):
    default = "" if default is None else str(default)
    while True:
        if secret:
            shown = f" [{T('keep_current')}]" if default else ""
            val = getpass.getpass(f"  {label}{shown}: ")
        else:
            shown = f" [{default}]" if default else ""
            val = input(f"  {label}{shown}: ").strip()
        if not val:
            val = default
        if required and not val:
            print("    " + red(T("value_required")))
            continue
        if val and validator:
            err = validator(val)
            if err:
                print("    " + red(err))
                continue
        return val


def ask_yn(label, default):
    hint = T("yn_default_yes") if default else T("yn_default_no")
    while True:
        val = input(f"  {label} {hint} ").strip().lower()
        if not val:
            return default
        if val in YES:
            return True
        if val in NO:
            return False
        print("    " + red(T("yn_invalid")))


def ask_choice(label, options, default_index=0):
    """options: list of (value, text). Returns the selected value."""
    print(f"  {bold(label)}")
    for i, (_, text) in enumerate(options, 1):
        print(f"    {i}) {text}")
    while True:
        val = input(f"  > [{default_index + 1}] ").strip()
        if not val:
            return options[default_index][0]
        if val.isdigit() and 1 <= int(val) <= len(options):
            return options[int(val) - 1][0]
        print("    " + red(T("choice_invalid")))


def v_url(v):
    return None if re.match(r"^https?://[^\s/]+", v) else T("invalid_url")


def v_port(v):
    return None if v.isdigit() and 0 < int(v) < 65536 else T("invalid_port")


def v_dbhost(v):
    return T("dbhost_localhost") if v.strip().lower() == "localhost" else None


def v_dbname(v):
    return None if re.fullmatch(r"[A-Za-z0-9_$-]+", v) else T("invalid_dbname")


def v_cryptkey(v):
    try:
        key = base64.b64decode(v, validate=True)
    except ValueError:
        return T("cryptkey_not_b64")
    return None if len(key) == 32 else T("cryptkey_len", n=len(key))


def str_to_bool(value):
    val = str(value).strip().lower()
    if val in ("yes", "y", "true", "t", "1", "oui", "o", "ja", "j", "si", "sí", "s"):
        return True
    if val in ("no", "n", "false", "f", "0", "non", "nein"):
        return False
    raise argparse.ArgumentTypeError(f"Boolean value expected (true/false), got: {value}")


# ─────────────────────────────────────────────────────────────────────────────
# Generic helpers (INI, DB, network)
# ─────────────────────────────────────────────────────────────────────────────
def new_cp():
    # No interpolation: passwords containing '%' must not break the parser.
    cp = configparser.RawConfigParser(strict=False)
    cp.optionxform = str
    return cp


def read_ini(*paths):
    cp = new_cp()
    for path in paths:
        if os.path.isfile(path):
            try:
                cp.read(path, encoding="utf-8")
            except (configparser.Error, OSError, UnicodeDecodeError):
                pass
    return cp


def ini_get(cp, section, key, default=""):
    try:
        return cp.get(section, key)
    except (configparser.NoSectionError, configparser.NoOptionError):
        return default


def to_int(v, default):
    try:
        return int(v)
    except (TypeError, ValueError):
        return default


def medulla_db_settings():
    cp = read_ini(XMPPMASTER_INI, XMPPMASTER_INI + ".local")
    return {"host": ini_get(cp, "database", "dbhost", "localhost") or "localhost",
            "port": to_int(ini_get(cp, "database", "dbport", "3306"), 3306),
            "user": ini_get(cp, "database", "dbuser", "mmc") or "mmc",
            "password": ini_get(cp, "database", "dbpasswd", "")}


def db_connect(host, port, user, password, database=None):
    kw = dict(host=host, port=int(port), user=user, password=password or "",
              connection_timeout=TIMEOUT)
    if database:
        kw["database"] = database
    return mysql.connector.connect(**kw)


def can_create_server(conn):
    """CREATE SERVER needs a global (ON *.*) SUPER / FEDERATED ADMIN (MariaDB >= 10.5.2) or ALL privilege."""
    try:
        rows = db_query(conn, "SHOW GRANTS FOR CURRENT_USER()")
    except DBError:
        return False
    for (grant,) in rows:
        m = re.match(r"GRANT\s+(.+?)\s+ON\s+\*\.\*\s+TO\s", grant, re.I)
        if m and any(x.strip().upper() in ("ALL", "ALL PRIVILEGES", "SUPER", "FEDERATED ADMIN")
                     for x in m.group(1).split(",")):
            return True
    return False


def medulla_admin_connect(database="xmppmaster"):
    """Connection to the LOCAL Medulla MariaDB allowed to create the federated server.
    1) the Medulla account (xmppmaster.ini) if it has the privilege;
    2) otherwise root through the local unix socket (the script runs as root, Debian root uses unix_socket).
    Returns (conn, account). Raises DBError / PermissionError when neither works."""
    s = medulla_db_settings()
    conn = db_connect(database=database, **s)
    if can_create_server(conn):
        return conn, s["user"]
    try:
        socket_path = db_query(conn, "SELECT @@socket")[0][0]
    except DBError:
        socket_path = None
    conn.close()
    if s["host"] in ("localhost", "127.0.0.1", "::1") and os.geteuid() == 0 and socket_path:
        try:
            root = mysql.connector.connect(unix_socket=socket_path, user="root", database=database,
                                           connection_timeout=TIMEOUT)
            if can_create_server(root):
                return root, "root"
            root.close()
        except DBError:
            pass
    raise PermissionError(T("fed_priv_ko", user=s["user"]))


def db_query(conn, sql, args=None):
    cur = conn.cursor()
    try:
        cur.execute(sql, args or ())
        return cur.fetchall() if cur.with_rows else []
    finally:
        cur.close()


def read_saas():
    try:
        conn = db_connect(database="admin", **medulla_db_settings())
        try:
            names = tuple(SAAS_DESCRIPTIONS)
            rows = db_query(conn, "SELECT setting_name, setting_value FROM saas_application WHERE setting_name IN ("
                                  + ",".join(["%s"] * len(names)) + ")", names)
        finally:
            conn.close()
        return {name: (value or "") for name, value in rows}, None
    except DBError as e:
        return {}, short(e)


def sql_literal(s):
    return "'" + str(s).replace("\\", "\\\\").replace("'", "\\'") + "'"


def like_match(pattern, value):
    """MySQL LIKE pattern match (used for database-level GRANTs such as `glpi%`)."""
    rx, i = "", 0
    while i < len(pattern):
        ch = pattern[i]
        if ch == "\\" and i + 1 < len(pattern):
            rx += re.escape(pattern[i + 1])
            i += 2
            continue
        rx += ".*" if ch == "%" else "." if ch == "_" else re.escape(ch)
        i += 1
    return re.fullmatch(rx, value, re.I) is not None


def url_host_port(url):
    u = urlparse(url or "")
    return u.hostname, u.port or (443 if u.scheme == "https" else 80)


def local_ip_towards(host, port):
    """Source IP Medulla uses to reach host (no packet is actually sent)."""
    if not host:
        return None
    try:
        family = socket.getaddrinfo(host, port)[0][0]
        s = socket.socket(family, socket.SOCK_DGRAM)
        try:
            s.connect((host, int(port)))
            return s.getsockname()[0]
        finally:
            s.close()
    except OSError:
        return None


def run(cmd, timeout=60):
    try:
        return subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
                              universal_newlines=True, timeout=timeout)
    except (OSError, subprocess.TimeoutExpired) as e:
        return subprocess.CompletedProcess(cmd, 1, "", str(e))


def glpi_decrypt(key_b64, data_b64):
    """Decrypt a value encrypted by GLPI (sodium XChaCha20-Poly1305, nonce used as AD)."""
    raw = base64.b64decode(data_b64)
    key = base64.b64decode(key_b64)
    nonce, ciphertext = raw[:24], raw[24:]
    return crypto_aead_xchacha20poly1305_ietf_decrypt(ciphertext, nonce, nonce, key).decode("utf-8")


def classify_token(value):
    """How a token is stored in GLPI. Returns (kind, clear_value):
       empty | plain (usable as is) | hashed | encrypted | unknown."""
    v = (value or "").strip()
    if not v:
        return "empty", None
    # A GLPI token is 40 random [a-zA-Z0-9] characters: a lowercase-hex string of a digest
    # length (md5 / sha1 / sha256 / sha512) is in practice a hash, not a token.
    if v.startswith(("$2y$", "$2a$", "$2b$", "$argon2")) or re.fullmatch(r"[0-9a-f]{32}|[0-9a-f]{40}|[0-9a-f]{64}|[0-9a-f]{128}", v):
        return "hashed", None
    if re.fullmatch(r"[A-Za-z0-9]{20,64}", v):
        return "plain", v
    try:
        raw = base64.b64decode(v, validate=True)
        if len(raw) > 24 + 16:          # sodium nonce + tag + payload (GLPIKey)
            return "encrypted", None
    except ValueError:
        pass
    return "unknown", None


def glpi_token_rows(conn, api_user):
    """Raw token values from the external GLPI: MMC API client and API user."""
    out = {}
    try:
        rows = db_query(conn, "SELECT app_token FROM glpi_apiclients WHERE name=%s", (MMC_API_CLIENT,))
        out["app"] = ("missing", None) if not rows else classify_token(rows[0][0])
    except DBError:
        pass
    if api_user:
        try:
            rows = db_query(conn, "SELECT api_token FROM glpi_users WHERE name=%s", (api_user,))
            out["user"] = ("missing", None) if not rows else classify_token(rows[0][0])
        except DBError:
            pass
    return out


def probe_glpi_tokens(p, quiet=False):
    """Read the MMC client and API user tokens on the external GLPI database (never localhost)."""
    if not p.db_host or v_dbhost(p.db_host):
        return {}
    try:
        conn = db_connect(p.db_host, p.db_port, p.db_user, p.db_pass, p.db_name)
    except DBError as e:
        if not quiet:
            print(f"    {yellow('[!]')} {T('probe_ko', err=short(e, 120))}")
        return {}
    try:
        return glpi_token_rows(conn, p.api_user)
    finally:
        conn.close()


def token_from_glpi(which, found, current, interactive, user=""):
    """which = 'app' | 'user'. Clear token in GLPI -> used as is (goes to saas_application).
    Otherwise -> the clear value must be entered (interactive) or provided (--apiapptoken...)."""
    what = T("tok_app", name=MMC_API_CLIENT) if which == "app" else T("tok_user", user=user)
    label = T("lbl_app_token") if which == "app" else T("lbl_user_token")
    kind, clear = found if found else (None, None)
    if kind == "plain":
        print(f"    {green('[✓]')} {T('token_autofill', what=what)}")
        return clear
    if kind == "missing":
        msg = T("mmc_client_missing", name=MMC_API_CLIENT) if which == "app" else T("apiuser_missing", user=user)
        print(f"    {yellow('[!]')} {msg}")
    elif kind:
        print(f"    {yellow('[!]')} {T('token_must_enter', what=what, kind=T('token_kind_' + kind))}")
    if interactive:
        return ask(label, current, secret=True)
    return current


# ─────────────────────────────────────────────────────────────────────────────
# Parameters
# ─────────────────────────────────────────────────────────────────────────────
class Params:
    DEFAULTS = dict(url="", db_host="", db_port=3306, db_name="glpi", db_user="", db_pass="",
                    api_url="", api_user="", api_pass="", app_token="", user_token="",
                    crypt_key="", readonly=False, inv_forward=True, inv_forward_url="",
                    inv_plugin="glpiinventory", inv_agent="glpiagent",
                    inv_agent_disabled=False, verify_ssl=True,
                    glpi_major=None)

    def __init__(self, **kw):
        for k, v in self.DEFAULTS.items():
            setattr(self, k, kw.get(k, v))


def external_glpi_state():
    """An external GLPI is connected only if [main] dbhost in glpi.ini.local is set and is not localhost.
    Returns (connected, dbhost, dbport, dbname)."""
    cp = read_ini(GLPI_INI_LOCAL)
    host = ini_get(cp, "main", "dbhost", "").strip()
    connected = bool(host) and host.lower() != "localhost"
    return (connected, host, to_int(ini_get(cp, "main", "dbport"), 3306),
            ini_get(cp, "main", "dbname", "") or "glpi")


def print_glpi_state():
    connected, host, port, name = external_glpi_state()
    if connected:
        print("  " + green(T("state_connected", host=host, port=port, db=name)))
    else:
        print("  " + yellow(T("state_not_connected", host=host or T("not_set"), file=GLPI_INI_LOCAL)))
    return connected


def load_current_params():
    """Read the current Medulla configuration."""
    p = Params()
    cp = read_ini(GLPI_INI, GLPI_INI_LOCAL)
    p.db_host = ini_get(cp, "main", "dbhost")
    p.db_port = to_int(ini_get(cp, "main", "dbport"), 3306)
    p.db_name = ini_get(cp, "main", "dbname") or "glpi"
    p.db_user = ini_get(cp, "main", "dbuser")
    p.db_pass = ini_get(cp, "main", "dbpasswd")
    p.readonly = ini_get(cp, "main", "dbreadonly", "0").strip() == "1"
    p.api_url = ini_get(cp, "webservices", "glpi_base_url")
    p.api_user = ini_get(cp, "webservices", "glpi_username")
    p.api_pass = ini_get(cp, "webservices", "glpi_password")
    p.url = (ini_get(cp, "authentication_glpi", "baseurl")
             or ini_get(cp, "main", "glpi_computer_uri").split("/front/")[0]).rstrip("/")

    inv = read_ini(SUBS_INV_INI, SUBS_INV_INI + ".local")
    fwd = ini_get(inv, "glpi", "enable_forward", None)
    if fwd is not None:
        p.inv_forward = fwd.strip().lower() in ("true", "1", "yes")
    p.inv_forward_url = ini_get(inv, "glpi", "url_to_forward")
    p.inv_plugin = ini_get(inv, "glpi", "inventory_plugin") or "glpiinventory"
    if os.path.isfile(CLIENT_INV_INI):
        agent = ini_get(read_ini(CLIENT_INV_INI), "parameters", "agent")
        p.inv_agent = "glpiagent" if agent == "glpiagent" else "fusioninventory"
    if p.readonly:
        p.inv_forward = False

    saas, err = read_saas()
    p.app_token = saas.get(SAAS_KEYS["app_token"], "")
    p.user_token = saas.get(SAAS_KEYS["user_token"], "")
    p.crypt_key = saas.get(SAAS_KEYS["crypt_key"], "")
    return p, err


def yesno(b):
    return T("yes") if b else T("no")


def secret(v):
    return "********" if v else T("not_set")


def token(v):
    return f"{v[:4]}… ({len(v)})" if v else T("not_set")


def show_params(p):
    rows = [("lbl_url", p.url), ("lbl_db_host", p.db_host), ("lbl_db_port", p.db_port),
            ("lbl_db_name", p.db_name), ("lbl_db_user", p.db_user),
            ("lbl_db_pass", secret(p.db_pass)), ("lbl_readonly", yesno(p.readonly)),
            ("lbl_api_url", p.api_url)]
    if not p.readonly:
        rows += [("lbl_api_user", p.api_user), ("lbl_api_pass", secret(p.api_pass)),
                 ("lbl_app_token", token(p.app_token)), ("lbl_user_token", token(p.user_token)),
                 ("lbl_crypt_key", secret(p.crypt_key))]
    rows.append(("lbl_inv_forward", yesno(p.inv_forward)))
    if p.inv_forward:
        rows += [("lbl_inv_url", p.inv_forward_url), ("lbl_inv_plugin", p.inv_plugin),
                 ("lbl_inv_agent", p.inv_agent)]
    rows += [("lbl_inv_agent_disabled", yesno(p.inv_agent_disabled)),
             ("lbl_verify_ssl", yesno(p.verify_ssl))]
    labels = [T(k).strip(" ?¿") for k, _ in rows]
    width = min(max(len(label) for label in labels), 40)
    for label, (_, value) in zip(labels, rows):
        print(f"    {label.ljust(width)} : {value if value not in ('', None) else T('not_set')}")


def validate_params(p, rep):
    rep.section(T("sec_params"))
    show_params(p)
    ok = True
    if p.readonly and p.inv_forward:
        rep.fail(T("readonly_forward_conflict"), fix="params")
        ok = False
    if p.db_host and v_dbhost(p.db_host):
        rep.fail(v_dbhost(p.db_host), fix="params")
        ok = False
    required = [("lbl_url", p.url), ("lbl_db_host", p.db_host), ("lbl_db_name", p.db_name),
                ("lbl_db_user", p.db_user), ("lbl_api_url", p.api_url)]
    if not p.readonly:
        required += [("lbl_api_user", p.api_user), ("lbl_api_pass", p.api_pass),
                     ("lbl_app_token", p.app_token), ("lbl_user_token", p.user_token)]
    if p.inv_forward:
        required.append(("lbl_inv_url", p.inv_forward_url))
    missing = [T(k).strip(" ?¿") for k, v in required if not v]
    if missing:
        rep.fail(T("param_missing", name=", ".join(missing)), fix="params")
        ok = False
    else:
        rep.ok(T("params_complete"))
    return ok


# ─────────────────────────────────────────────────────────────────────────────
# Checks
# ─────────────────────────────────────────────────────────────────────────────
class Checker:
    def __init__(self, p, rep):
        self.p, self.rep = p, rep
        self.conn = None
        self.glpi_version = None
        self.glpi_major = None
        self.glpi_cfg = {}
        self.missing_views = []
        self.ssl_failed = set()

    def close(self):
        if self.conn is not None:
            try:
                self.conn.close()
            except Exception:
                pass
            self.conn = None

    # ── Local prerequisites ─────────────────────────────────────────────────
    def check_prerequisites(self, require_root):
        r = self.rep
        r.section(T("sec_prereq"))
        critical_ok = True
        if sys.version_info < (3, 7):
            r.fail(T("python_too_old", v=sys.version.split()[0]))
            critical_ok = False
        for mod, pkg, present in (("mysql.connector", "python3-mysql.connector", mysql is not None),
                                  ("requests", "python3-requests", requests is not None)):
            if present:
                r.ok(T("module_ok", mod=mod))
            else:
                r.fail(T("module_missing", mod=mod), T("hint_apt", pkg=pkg))
                critical_ok = False
        if crypto_aead_xchacha20poly1305_ietf_decrypt:
            r.ok(T("module_ok", mod="nacl"))
        else:
            r.warn(T("nacl_missing"), T("hint_apt", pkg="python3-nacl"))
        if os.geteuid() == 0:
            r.ok(T("root_ok"))
        elif require_root:
            r.fail(T("root_required"))
            critical_ok = False
        else:
            r.warn(T("root_recommended"))
        for tool in ("systemctl", "mysql"):
            if shutil.which(tool):
                r.ok(T("tool_ok", tool=tool))
            else:
                r.warn(T("tool_missing", tool=tool))
        return critical_ok

    def check_medulla_db(self):
        r = self.rep
        r.section(T("sec_medulla_db"))
        s = medulla_db_settings()
        r.info(T("medulla_db_target", host=s["host"], port=s["port"], user=s["user"]))
        version, text = medulla_version()
        if version:
            r.info(T("medulla_version", v=text))
        else:
            r.warn(T("medulla_version_unknown", file=MEDULLA_VERSION_FILE))
        try:
            conn = db_connect(database="xmppmaster", **s)
        except DBError as e:
            r.fail(T("medulla_db_ko", err=short(e)), T("hint_check_file", file=XMPPMASTER_INI + ".local"))
            return False
        try:
            r.ok(T("medulla_db_ok"))
            try:
                rows = db_query(conn, "SELECT SUPPORT FROM information_schema.ENGINES WHERE ENGINE='FEDERATED'")
                if rows and str(rows[0][0]).upper() in ("YES", "DEFAULT"):
                    r.ok(T("federated_engine_ok"))
                else:
                    r.fail(T("federated_engine_ko"), [T("hint_federated_engine1"),
                                                      "INSTALL SONAME 'ha_federatedx';",
                                                      T("hint_federated_engine2")])
            except DBError as e:
                r.warn(T("check_error", err=short(e)))
            try:
                admin, who = medulla_admin_connect()
                admin.close()
                r.ok(T("fed_priv_ok", user=who) if who == s["user"] else T("fed_priv_root", user=s["user"]))
            except (DBError, PermissionError):
                r.fail(T("fed_priv_ko", user=s["user"]),
                       [T("hint_fed_priv"),
                        f"GRANT FEDERATED ADMIN ON *.* TO '{s['user']}'@'{s['host']}';",
                        T("hint_fed_priv_old")])
            try:
                db_query(conn, "SELECT COUNT(*) FROM admin.saas_application")
                r.ok(T("admin_db_ok"))
            except DBError as e:
                r.fail(T("admin_db_ko", err=short(e)))
        finally:
            conn.close()
        return True

    # ── Remote: network + GLPI database ─────────────────────────────────────
    def check_network(self):
        r, p = self.rep, self.p
        r.section(T("sec_network"))
        try:
            ip = socket.getaddrinfo(p.db_host, p.db_port, proto=socket.IPPROTO_TCP)[0][4][0]
            r.ok(T("dns_ok", host=p.db_host, ip=ip))
        except (socket.gaierror, UnicodeError) as e:
            r.fail(T("dns_ko", host=p.db_host, err=e), T("hint_dns"), fix="params")
            return False
        src = local_ip_towards(p.db_host, p.db_port)
        if src:
            r.info(T("source_ip", ip=src))
        try:
            with socket.create_connection((p.db_host, int(p.db_port)), timeout=TIMEOUT):
                r.ok(T("tcp_ok", host=p.db_host, port=p.db_port))
        except OSError as e:
            r.fail(T("tcp_ko", host=p.db_host, port=p.db_port, err=e),
                   [T("hint_bind_address"), T("hint_firewall", ip=src or "Medulla", port=p.db_port)])
            return False
        return True

    def _grant_hint(self):
        p = self.p
        ip = local_ip_towards(p.db_host, p.db_port) or "<MEDULLA_IP>"
        privs = "SELECT, SHOW VIEW" if p.readonly else "ALL PRIVILEGES"
        return [T("hint_grant"),
                f"CREATE USER IF NOT EXISTS '{p.db_user}'@'{ip}' IDENTIFIED BY '********';",
                f"GRANT {privs} ON `{p.db_name}`.* TO '{p.db_user}'@'{ip}';"]

    def _db_hints(self, e):
        p = self.p
        errno = getattr(e, "errno", None)
        if errno == 2003:
            return [T("hint_db_unreachable", host=p.db_host, port=p.db_port), T("hint_bind_address")]
        if errno == 1130:
            return [T("hint_host_not_allowed", user=p.db_user)] + self._grant_hint()
        if errno == 1045:
            return [T("hint_access_denied", user=p.db_user)] + self._grant_hint()
        if errno == 1044:
            return self._grant_hint()
        if errno == 2005:
            return [T("hint_dns")]
        return []

    def check_glpi_db(self):
        r, p = self.rep, self.p
        r.section(T("sec_glpi_db"))
        try:
            conn = db_connect(p.db_host, p.db_port, p.db_user, p.db_pass)
        except DBError as e:
            r.fail(T("glpi_db_ko", err=short(e)), self._db_hints(e),
                   fix="params" if getattr(e, "errno", None) in (1045, 1049, 2005) else None)
            return False
        r.ok(T("glpi_db_ok", user=p.db_user, host=p.db_host, port=p.db_port))
        try:
            r.info(T("db_server_version", v=db_query(conn, "SELECT VERSION()")[0][0]))
            if not db_query(conn, "SELECT SCHEMA_NAME FROM information_schema.SCHEMATA WHERE SCHEMA_NAME=%s",
                            (p.db_name,)):
                r.fail(T("glpi_dbname_ko", db=p.db_name), self._grant_hint(), fix="params")
                conn.close()
                return False
            conn.database = p.db_name
            r.ok(T("glpi_dbname_ok", db=p.db_name))
        except DBError as e:
            r.fail(T("check_error", err=short(e)))
            conn.close()
            return False
        self.conn = conn
        return True

    def check_glpi_version(self):
        r = self.rep
        r.section(T("sec_version"))
        try:
            rows = db_query(self.conn,
                            "SELECT context, name, value FROM glpi_configs WHERE "
                            "(context='core' AND name IN ('version','dbversion','url_base','enable_api',"
                            "'enable_api_login_credentials','enable_api_login_external_token')) "
                            "OR (context='inventory' AND name='enabled_inventory')")
        except DBError as e:
            r.fail(T("not_glpi_db", err=short(e)))
            return False
        self.glpi_cfg = {f"{c}.{n}": v for c, n, v in rows}
        version = self.glpi_cfg.get("core.version") or ""
        m = re.match(r"(\d+)\.(\d+)", version)
        if not m:
            r.fail(T("glpi_version_unknown"))
            return False
        self.glpi_version, self.glpi_major = version, int(m.group(1))
        self.p.glpi_major = self.glpi_major
        if self.glpi_major in SQL_FILES:
            r.ok(T("glpi_version_ok", v=version))
        else:
            r.fail(T("glpi_version_unsupported", v=version), T("hint_supported_versions"))
        dbv = (self.glpi_cfg.get("core.dbversion") or "").split("@")[0]
        if dbv and dbv != version:
            r.warn(T("glpi_dbversion_mismatch", v=version, dbv=dbv), T("hint_glpi_update_db"))
        if self.glpi_major in SQL_FILES:
            self.print_sql_notice()
        return True

    def print_sql_notice(self):
        p = self.p
        url = SQL_FILES[self.glpi_major]
        fname = url.rsplit("/", 1)[1]
        box([T("sql_notice_title", major=self.glpi_major),
             "",
             T("sql_notice_body", file=fname),
             f"  {url}",
             "",
             T("sql_notice_backup"),
             f"  wget -O {fname} {url}",
             f"  mysql -h {p.db_host} -P {p.db_port} -u {p.db_user} -p {p.db_name} < {fname}",
             "",
             T("sql_notice_after")])

    def _sql_hint(self):
        return T("hint_apply_sql", url=SQL_FILES[self.glpi_major]) if self.glpi_major in SQL_FILES else None

    def check_schema(self):
        r, p = self.rep, self.p
        r.section(T("sec_schema"))
        try:
            rows = db_query(self.conn, "SELECT TABLE_NAME, TABLE_TYPE FROM information_schema.TABLES "
                                       "WHERE TABLE_SCHEMA=%s", (p.db_name,))
        except DBError as e:
            r.fail(T("check_error", err=short(e)))
            return
        objs = {name: ttype for name, ttype in rows}
        tables = sorted(set(REQUIRED_TABLES) | {remote for remote, _ in FEDERATED_TABLES.values()})
        missing = [t for t in tables if t not in objs]
        if missing:
            hint = T("hint_glpiinventory") if "glpi_plugin_glpiinventory_collects" in missing else None
            r.fail(T("tables_missing", n=len(missing), list=", ".join(missing)), hint)
        else:
            r.ok(T("tables_ok", n=len(tables)))

        if machines_needs_extra_columns() and "glpi_computers" in objs:
            try:
                remote_cols = {c for (c,) in db_query(self.conn, "SELECT COLUMN_NAME FROM information_schema.COLUMNS "
                                                                 "WHERE TABLE_SCHEMA=%s AND TABLE_NAME='glpi_computers'",
                                                      (p.db_name,))}
                absent = [c for c in MACHINES_EXTRA_COLUMNS if c not in remote_cols]
                if absent:
                    r.fail(T("glpi_computers_cols_missing", cols=", ".join(absent)))
            except DBError as e:
                r.warn(T("check_error", err=short(e)))
        self.missing_views = [v for v in REQUIRED_VIEWS if objs.get(v) != "VIEW"]
        if self.missing_views:
            r.fail(T("views_missing", n=len(self.missing_views), list=", ".join(self.missing_views)),
                   self._sql_hint(), fix="sql")
        else:
            r.ok(T("views_ok", n=len(REQUIRED_VIEWS)))
        broken = []
        for view in REQUIRED_VIEWS:
            if objs.get(view) == "VIEW":
                try:
                    db_query(self.conn, f"SELECT 1 FROM `{view}` LIMIT 1")
                except DBError as e:
                    broken.append(view)
                    r.info(f"{view}: {short(getattr(e, 'msg', e), 160)}")
        if broken:
            r.fail(T("views_broken", list=", ".join(broken)), self._sql_hint(), fix="sql")
            self.missing_views += broken
        elif not self.missing_views:
            r.ok(T("views_query_ok"))

    def check_privileges(self):
        r, p = self.rep, self.p
        r.section(T("sec_privileges"))
        try:
            rows = db_query(self.conn, "SHOW GRANTS FOR CURRENT_USER()")
        except DBError as e:
            r.warn(T("check_error", err=short(e)))
            return
        privs = set()
        for (grant,) in rows:
            m = re.match(r"GRANT\s+(.+?)\s+ON\s+(?:TABLE\s+)?(\S+)\s+TO\s", grant, re.I)
            if not m:
                continue
            dbpart, _, tbl = m.group(2).replace("`", "").partition(".")
            if tbl != "*" or (dbpart != "*" and not like_match(dbpart, p.db_name)):
                continue
            for priv in m.group(1).split(","):
                priv = priv.strip().upper()
                privs.add("ALL" if priv.startswith("ALL") else priv)
        r.info(T("grants_found", db=p.db_name, list=", ".join(sorted(privs)) or "-"))

        def has(x):
            return "ALL" in privs or x in privs
        needed = ["SELECT"] + ([] if p.readonly else ["INSERT", "UPDATE", "DELETE"])
        missing = [x for x in needed if not has(x)]
        if missing:
            r.warn(T("grants_missing", list=", ".join(missing)), self._grant_hint())
        else:
            r.ok(T("grants_ok"))
        if not (has("CREATE VIEW") and has("DROP")):
            r.info(T("grants_no_create_view"))

    def check_plugins(self):
        r, p = self.rep, self.p
        r.section(T("sec_plugins"))
        try:
            rows = db_query(self.conn, "SELECT directory, version, state FROM glpi_plugins "
                                       "WHERE directory IN ('glpiinventory','fusioninventory')")
        except DBError as e:
            r.warn(T("check_error", err=short(e)))
            return
        plugins = {d: (v, to_int(s, 0)) for d, v, s in rows}
        for name, (version, state) in plugins.items():
            r.info(T("plugin_state", name=name, v=version,
                     state=T("plugin_on") if state == 1 else T("plugin_off", s=state)))
        if p.inv_forward and p.inv_plugin == "fusioninventory" and (self.glpi_major or 0) >= 10:
            r.fail(T("fusion_incompatible"), T("hint_use_glpiinventory"))
        if p.inv_forward:
            st = plugins.get(p.inv_plugin)
            if not st:
                r.fail(T("plugin_missing", name=p.inv_plugin), T("hint_glpiinventory"))
            elif st[1] != 1:
                r.fail(T("plugin_inactive", name=p.inv_plugin), T("hint_activate_plugin"))
            else:
                r.ok(T("plugin_ok", name=p.inv_plugin, v=st[0]))
        elif not plugins:
            r.info(T("plugin_none"))

    def check_glpi_settings(self):
        r, p, cfg = self.rep, self.p, self.glpi_cfg
        r.section(T("sec_settings"))
        base = (cfg.get("core.url_base") or "").rstrip("/")
        if base and p.url and base.lower() != p.url.rstrip("/").lower():
            r.warn(T("url_base_mismatch", glpi=base, medulla=p.url))
        elif base:
            r.ok(T("url_base_ok", url=base))
        if not p.readonly:
            for key, msg in (("core.enable_api", "api_enabled"),
                             ("core.enable_api_login_credentials", "api_login_cred"),
                             ("core.enable_api_login_external_token", "api_login_token")):
                if cfg.get(key) == "1":
                    r.ok(T(msg + "_ok"))
                else:
                    r.fail(T(msg + "_ko"), T("hint_glpi_api_setup"))
        if p.inv_forward:
            value = cfg.get("inventory.enabled_inventory")
            if value == "1":
                r.ok(T("inventory_enabled_ok"))
            elif value is None:
                r.warn(T("inventory_enabled_unknown"))
            else:
                r.fail(T("inventory_enabled_ko"), T("hint_enable_inventory"))

    def check_api_objects(self):
        r, p = self.rep, self.p
        if p.readonly:
            return
        r.section(T("sec_api_objects"))
        self._check_mmc_client()
        if p.api_user:
            self._check_api_user()

    def _check_token(self, what, raw, configured, hint_empty):
        """GLPI token -> must be in clear to be copied into saas_application, and equal to it."""
        r = self.rep
        kind, clear = classify_token(raw)
        if kind == "empty":
            r.fail(T("token_empty", what=what), hint_empty)
        elif kind == "plain":
            r.ok(T("token_plain", what=what))
            if configured == clear:
                r.ok(T("token_matches_saas", what=what))
            elif not configured:
                r.fail(T("token_saas_empty_copyable", what=what), T("hint_fix_mode"), fix="auto")
            else:
                r.fail(T("token_differs_saas", what=what), T("hint_fix_mode"), fix="auto")
        else:
            # Not copyable from GLPI: the value configured for Medulla must itself exist and be in clear.
            r.warn(T("token_not_plain", what=what, kind=T("token_kind_" + kind)), T("hint_token_enter_clear"))
            if not configured:
                r.fail(T("token_saas_missing", what=what), T("hint_token_enter_clear"), fix="params")
            elif classify_token(configured)[0] != "plain":
                r.fail(T("token_saas_not_clear", what=what), T("hint_token_enter_clear"), fix="params")
            elif kind == "encrypted" and self._decrypts_to(raw, configured) is not None:
                if self._decrypts_to(raw, configured):
                    r.ok(T("token_matches_saas_decrypted", what=what))
                else:
                    r.fail(T("token_differs_saas_decrypted", what=what), T("hint_token_enter_clear"), fix="params")
            else:
                r.info(T("token_saas_unverifiable", what=what))

    def _decrypts_to(self, raw, configured):
        """True/False if the GLPI key can decrypt raw (compared to configured); None if not decryptable."""
        key = self.p.crypt_key
        if not (crypto_aead_xchacha20poly1305_ietf_decrypt and key and v_cryptkey(key) is None):
            return None
        try:
            return glpi_decrypt(key, raw) == configured
        except Exception:
            return None

    def _check_mmc_client(self):
        r, p = self.rep, self.p
        try:
            rows = db_query(self.conn, "SELECT name, is_active, ipv4_range_start, ipv4_range_end, app_token "
                                       "FROM glpi_apiclients WHERE name=%s", (MMC_API_CLIENT,))
        except DBError as e:
            r.warn(T("check_error", err=short(e)))
            return
        if not rows:
            r.fail(T("mmc_client_missing", name=MMC_API_CLIENT), T("hint_create_mmc", name=MMC_API_CLIENT))
            return
        if len(rows) > 1:
            r.warn(T("mmc_client_multiple", n=len(rows), name=MMC_API_CLIENT))
        name, active, start, end, app_token = rows[0]
        if to_int(active, 0) == 1:
            r.ok(T("mmc_client_ok", name=name))
        else:
            r.fail(T("apiclient_inactive", name=name), T("hint_glpi_api_setup"))
        src = local_ip_towards(*url_host_port(p.api_url))
        if start and end and src:
            try:
                ipn = int(ipaddress.IPv4Address(src))
                rng = f"{ipaddress.IPv4Address(int(start))} - {ipaddress.IPv4Address(int(end))}"
                if int(start) <= ipn <= int(end):
                    r.ok(T("apiclient_ip_ok", ip=src, range=rng))
                else:
                    r.warn(T("apiclient_ip_ko", ip=src, range=rng), T("hint_apiclient_ip"))
            except ValueError:
                pass
        elif not start:
            r.info(T("apiclient_no_iprange"))
        self._check_token(T("tok_app", name=MMC_API_CLIENT), app_token, p.app_token,
                          T("hint_create_mmc", name=MMC_API_CLIENT))

    def _check_api_user(self):
        r, p = self.rep, self.p
        try:
            user = db_query(self.conn, "SELECT is_active, is_deleted, api_token FROM glpi_users WHERE name=%s",
                            (p.api_user,))
        except DBError as e:
            r.warn(T("check_error", err=short(e)))
            return
        if not user:
            r.fail(T("apiuser_missing", user=p.api_user), fix="params")
            return
        active, deleted, api_token = user[0]
        if to_int(deleted, 0):
            r.fail(T("apiuser_deleted", user=p.api_user))
        elif not to_int(active, 0):
            r.fail(T("apiuser_inactive", user=p.api_user))
        else:
            r.ok(T("apiuser_ok", user=p.api_user))
        self._check_token(T("tok_user", user=p.api_user), api_token, p.user_token,
                          T("hint_regen_user_token", user=p.api_user))

    def check_crypt_key(self):
        r, p = self.rep, self.p
        if p.readonly:
            return
        r.section(T("sec_cryptkey"))
        if p.glpi_major == 10:
            if not p.crypt_key:
                r.fail(T("cryptkey_glpi10_empty", value=CRYPT_KEY_GLPI10), T("hint_fix_mode"), fix="auto")
            else:
                r.ok(T("cryptkey_glpi10_ok"))
            return
        if not p.crypt_key or p.crypt_key == CRYPT_KEY_GLPI10:
            r.fail(T("cryptkey_missing"), T("cryptkey_howto"), fix="params")
            return
        err = v_cryptkey(p.crypt_key)
        if err:
            r.fail(err, T("cryptkey_howto"), fix="params")
            return
        r.ok(T("cryptkey_format_ok"))
        if not crypto_aead_xchacha20poly1305_ietf_decrypt:
            r.info(T("cryptkey_no_nacl"))
            return
        if self.conn is None:
            return
        samples = []
        for sql in ("SELECT value FROM glpi_configs WHERE context='core' AND name IN ('smtp_passwd','proxy_passwd') "
                    "AND value IS NOT NULL AND value<>''",
                    "SELECT rootdn_passwd FROM glpi_authldaps WHERE rootdn_passwd IS NOT NULL "
                    "AND rootdn_passwd<>'' LIMIT 3"):
            try:
                samples += [row[0] for row in db_query(self.conn, sql)]
            except DBError:
                pass
        if not samples:
            r.info(T("cryptkey_no_sample"))
            return
        for sample in samples:
            try:
                glpi_decrypt(p.crypt_key, sample)
                r.ok(T("cryptkey_match"))
                return
            except Exception:
                continue
        r.fail(T("cryptkey_mismatch"), T("cryptkey_howto"), fix="params")

    # ── Remote: HTTP ─────────────────────────────────────────────────────────
    def _http(self, url, **kw):
        host = urlparse(url).hostname
        verify = self.p.verify_ssl and host not in self.ssl_failed
        try:
            return requests.get(url, timeout=TIMEOUT, verify=verify, **kw), None
        except requests.exceptions.SSLError as e:
            self.ssl_failed.add(host)
            self.rep.fail(T("ssl_ko", url=url, err=short(e, 160)), [T("hint_ssl_ca"), T("hint_insecure")])
            return self._http(url, **kw)
        except requests.exceptions.RequestException as e:
            return None, short(e)

    def check_web(self):
        r, p = self.rep, self.p
        r.section(T("sec_web"))
        if not p.url:
            r.fail(T("param_missing", name=T("lbl_url")))
            return
        if p.url.startswith("http://"):
            r.warn(T("http_cleartext", url=p.url))
        resp, err = self._http(p.url)
        if resp is None:
            r.fail(T("url_unreachable", url=p.url, err=err), T("hint_firewall_web"))
        elif resp.status_code < 400:
            r.ok(T("url_reachable", url=p.url, code=resp.status_code))
        else:
            r.warn(T("url_http_code", url=p.url, code=resp.status_code))

    @staticmethod
    def _api_error(resp):
        try:
            data = resp.json()
            if isinstance(data, list):
                return " — ".join(str(x) for x in data)
        except ValueError:
            pass
        return resp.text.strip()[:200]

    def _kill_session(self, session_token):
        self._http(f"{self.p.api_url.rstrip('/')}/killSession",
                   headers={"Session-Token": session_token, "App-Token": self.p.app_token})

    def _eval_session(self, resp, err, kind, curl, full=False):
        r = self.rep
        if resp is None:
            r.fail(T(kind + "_ko", code="-", err=err), T("hint_firewall_web"))
            return
        if resp.status_code != 200:
            r.fail(T(kind + "_ko", code=resp.status_code, err=self._api_error(resp)), [T("hint_curl"), curl],
                   fix="params")
            return
        r.ok(T(kind + "_ok"))
        try:
            data = resp.json()
        except ValueError:
            data = {}
        if not isinstance(data, dict):
            return
        if full:
            profile = (data.get("session") or {}).get("glpiactiveprofile") or {}
            if profile.get("name"):
                r.info(T("api_profile", name=profile.get("name"), iface=profile.get("interface", "?")))
            if profile.get("interface") and profile.get("interface") != "central":
                r.warn(T("api_profile_helpdesk"), T("hint_profile"))
        if data.get("session_token"):
            self._kill_session(data["session_token"])

    def check_api(self):
        r, p = self.rep, self.p
        r.section(T("sec_api"))
        if not p.api_url:
            r.fail(T("param_missing", name=T("lbl_api_url")))
            return
        api = p.api_url.rstrip("/")
        base = (p.url or "").rstrip("/")
        if self.glpi_major == 10 and "apirest.php" not in api:
            r.warn(T("api_url_v10", url=api), T("hint_api_url", url=f"{base}/apirest.php"))
        if self.glpi_major == 11 and "api.php/v1" not in api and "apirest.php" not in api:
            r.warn(T("api_url_v11", url=api), T("hint_api_url", url=f"{base}/api.php/v1"))
        resp, err = self._http(api)
        if resp is None:
            r.fail(T("url_unreachable", url=api, err=err), T("hint_firewall_web"))
            return
        r.ok(T("url_reachable", url=api, code=resp.status_code))
        if p.readonly:
            r.info(T("api_skip_readonly"))
            return
        if p.api_user and p.api_pass and p.app_token:
            resp, err = self._http(f"{api}/initSession", auth=(p.api_user, p.api_pass),
                                   headers={"App-Token": p.app_token})
            self._eval_session(resp, err, "api_cred",
                               f'curl -u {p.api_user}:<PASSWORD> -H "App-Token: <APP_TOKEN>" {api}/initSession')
        if p.user_token and p.app_token:
            resp, err = self._http(f"{api}/initSession?get_full_session=true",
                                   headers={"App-Token": p.app_token,
                                            "Authorization": f"user_token {p.user_token}"})
            self._eval_session(resp, err, "api_token",
                               f'curl -H "App-Token: <APP_TOKEN>" -H "Authorization: user_token <USER_TOKEN>" '
                               f'"{api}/initSession?get_full_session=true"', full=True)

    def check_forward(self):
        r, p = self.rep, self.p
        if not p.inv_forward:
            return
        r.section(T("sec_forward"))
        if not p.inv_forward_url:
            r.fail(T("param_missing", name=T("lbl_inv_url")))
            return
        resp, err = self._http(p.inv_forward_url)
        if resp is None:
            r.fail(T("url_unreachable", url=p.inv_forward_url, err=err), T("hint_firewall_web"))
            return
        if resp.status_code in (200, 405):
            r.ok(T("url_reachable", url=p.inv_forward_url, code=resp.status_code))
        elif resp.status_code < 500:
            r.warn(T("url_http_code", url=p.inv_forward_url, code=resp.status_code))
        else:
            r.fail(T("url_http_code", url=p.inv_forward_url, code=resp.status_code))
        if "front/inventory.php" not in p.inv_forward_url:
            r.warn(T("forward_url_hint", url=f"{(p.url or '').rstrip('/')}/front/inventory.php"))

    # ── Local: Medulla side ──────────────────────────────────────────────────
    def check_medulla_config(self):
        r, p = self.rep, self.p
        r.section(T("sec_medulla_conf"))
        if not os.path.isfile(GLPI_INI_LOCAL):
            r.fail(T("file_missing", file=GLPI_INI_LOCAL), T("hint_fix_mode"))
        else:
            r.ok(T("file_ok", file=GLPI_INI_LOCAL))
            mode = os.stat(GLPI_INI_LOCAL).st_mode & 0o777
            if mode & 0o004:
                r.warn(T("file_world_readable", file=GLPI_INI_LOCAL, mode=oct(mode)),
                       T("hint_chmod", file=GLPI_INI_LOCAL))
        cp = read_ini(GLPI_INI, GLPI_INI_LOCAL)
        if ini_get(cp, "main", "disable", "1").strip() == "0":
            r.ok(T("glpi_plugin_enabled"))
        else:
            r.fail(T("glpi_plugin_disabled"), T("hint_fix_mode"))
        if p.readonly and p.inv_forward:
            r.fail(T("readonly_forward_conflict"), fix="params")

        expected = {"glpi_dbhost": p.db_host, "glpi_dbport": str(p.db_port), "glpi_dbname": p.db_name,
                    "glpi_dbuser": p.db_user, "glpi_dbpasswd": p.db_pass}
        for base in [SUBS_REG_INI] + ([SUBS_INV_INI] if p.inv_forward else []):
            local = base + ".local"
            cp2 = read_ini(base, local)
            diffs = [k for k, v in expected.items() if ini_get(cp2, "glpidatabase", k, None) != v]
            if diffs:
                r.fail(T("conf_mismatch", file=local, keys=", ".join(diffs)), T("hint_fix_mode"))
            else:
                r.ok(T("conf_consistent", file=local))
        if p.inv_forward:
            inv = read_ini(SUBS_INV_INI, SUBS_INV_INI + ".local")
            if ini_get(inv, "glpi", "enable_forward", "").strip().lower() not in ("true", "1", "yes"):
                r.fail(T("conf_mismatch", file=SUBS_INV_INI + ".local", keys="enable_forward"), T("hint_fix_mode"))
            agent = ini_get(read_ini(CLIENT_INV_INI), "parameters", "agent")
            if (p.inv_agent == "glpiagent") == (agent == "glpiagent"):
                r.ok(T("client_agent_ok", agent=p.inv_agent))
            else:
                r.warn(T("client_agent_mismatch", file=CLIENT_INV_INI, agent=p.inv_agent), T("hint_fix_mode"))
        reg = read_ini(REGAGENT_INI, REGAGENT_INI + ".local")
        if p.readonly != (ini_get(reg, "parameters", "check_uuidinventory", "").strip().lower() == "true"):
            r.warn(T("regagent_mismatch", file=REGAGENT_INI + ".local"), T("hint_fix_mode"))
        if not p.readonly:
            saas, err = read_saas()
            if err:
                r.fail(T("saas_read_ko", err=err), fix="manual")
            else:
                empty = [name for name in SAAS_KEYS.values()
                         if name != SAAS_KEYS["crypt_key"] and not saas.get(name)]
                if empty:
                    r.fail(T("saas_empty", list=", ".join(empty)), T("hint_fix_mode"))
                else:
                    r.ok(T("saas_ok"))
                type_api = saas.get("type_api", "")
                if not type_api:
                    r.fail(T("type_api_empty", value=SAAS_TYPE_API), T("hint_fix_mode"))
                elif type_api != SAAS_TYPE_API:
                    r.warn(T("type_api_other", value=type_api, expected=SAAS_TYPE_API))
                else:
                    r.ok(T("type_api_ok", value=type_api))
                saas_url = saas.get(SAAS_KEYS["api_url"], "")
                if saas_url and saas_url.rstrip("/") != (p.api_url or "").rstrip("/"):
                    r.warn(T("saas_url_mismatch", saas=saas_url, ini=p.api_url), T("hint_fix_mode"))

    def check_federated(self):
        r, p = self.rep, self.p
        r.section(T("sec_federated"))
        try:
            conn = db_connect(database="xmppmaster", **medulla_db_settings())
        except DBError as e:
            r.fail(T("medulla_db_ko", err=short(e)), fix="manual")
            return
        try:
            try:
                try:
                    admin, _ = medulla_admin_connect()
                except (DBError, PermissionError):
                    admin = conn      # may lack SELECT on mysql.servers -> reported as unreadable
                try:
                    rows = db_query(admin, "SELECT Host, Port, Db, Username FROM mysql.servers "
                                           "WHERE Server_name=%s", (FEDERATED_SERVER,))
                finally:
                    if admin is not conn:
                        admin.close()
                if not rows:
                    r.fail(T("fedserver_missing"), T("hint_fix_mode"))
                else:
                    host, port, db, user = rows[0]
                    diffs = [n for n, a, b in (("host", host, p.db_host), ("port", port, p.db_port),
                                               ("db", db, p.db_name), ("user", user, p.db_user))
                             if str(a) != str(b)]
                    if diffs:
                        r.fail(T("fedserver_mismatch", list=", ".join(diffs)), T("hint_fix_mode"))
                    else:
                        r.ok(T("fedserver_ok", host=host, port=port, db=db))
            except DBError as e:
                r.warn(T("fedserver_unreadable", err=short(e)))
            broken = []
            for table in FEDERATED_TABLES:
                try:
                    db_query(conn, f"SELECT 1 FROM `{table}` LIMIT 1")
                except DBError as e:
                    broken.append(f"{table}: {short(getattr(e, 'msg', e), 140)}")
            if broken:
                r.fail(T("fedtables_ko", n=len(broken)), broken + [T("hint_fix_mode")])
            else:
                r.ok(T("fedtables_ok", n=len(FEDERATED_TABLES)))
            if machines_needs_extra_columns():
                cols = {c for (c,) in db_query(conn, "SELECT COLUMN_NAME FROM information_schema.COLUMNS WHERE "
                                                     "TABLE_SCHEMA='xmppmaster' AND TABLE_NAME='local_glpi_machines'")}
                missing_cols = [c for c in MACHINES_EXTRA_COLUMNS if c not in cols]
                if cols and missing_cols:
                    r.fail(T("machines_cols_missing", cols=", ".join(missing_cols), v=medulla_version()[1]),
                           T("hint_fix_mode"))
                elif cols:
                    r.ok(T("machines_cols_ok", v=medulla_version()[1]))
                try:
                    n = db_query(conn, "SELECT COUNT(*) FROM local_glpi_machines "
                                       "WHERE is_deleted=0 AND is_template=0")[0][0]
                    r.info(T("glpi_machines_count", n=n))
                except DBError:
                    pass
            try:
                n = db_query(conn, "SELECT COUNT(*) FROM machines WHERE agenttype='machine'")[0][0]
                r.info(T("medulla_machines_count", n=n))
            except DBError:
                pass
        finally:
            conn.close()

    def check_services(self):
        r = self.rep
        r.section(T("sec_services"))
        if not shutil.which("systemctl"):
            r.warn(T("tool_missing", tool="systemctl"))
            return
        for svc in SERVICES:
            state = run(["systemctl", "is-active", svc]).stdout.strip()
            if state == "active":
                r.ok(T("service_ok", svc=svc))
            else:
                r.fail(T("service_ko", svc=svc, state=state or "?"), f"journalctl -u {svc} -n 50 --no-pager")

    # ── Orchestration ────────────────────────────────────────────────────────
    def run_remote(self, sql_hook=None):
        """All checks against the external GLPI (database, web, API)."""
        if self.p.db_host and self.check_network() and self.check_glpi_db():
            if self.check_glpi_version():
                snap = self.rep.snapshot()
                self.check_schema()
                while (sql_hook and self.missing_views and self.glpi_major in SQL_FILES
                       and sql_hook(self)):
                    self.rep.restore(snap)
                    self.rep.info(T("rechecking"))
                    self.check_schema()
                self.check_privileges()
                self.check_plugins()
                self.check_glpi_settings()
                self.check_api_objects()
        else:
            self.rep.info(T("skip_db_checks"))
        self.check_crypt_key()
        self.check_web()
        self.check_api()
        self.check_forward()

    def run_local(self):
        """Checks of what is configured on the Medulla server."""
        self.check_medulla_config()
        self.check_federated()
        self.check_services()


# ─────────────────────────────────────────────────────────────────────────────
# SQL file (glpi-100.sql / glpi-110.sql)
# ─────────────────────────────────────────────────────────────────────────────
def apply_sql_file(p, major, rep):
    url = SQL_FILES[major]
    fname = url.rsplit("/", 1)[1]
    try:
        resp = requests.get(url, timeout=60)
        resp.raise_for_status()
    except requests.exceptions.RequestException as e:
        rep.fail(T("sql_download_ko", url=url, err=short(e)))
        return False
    rep.ok(T("sql_download_ok", file=fname))
    fd, path = tempfile.mkstemp(suffix=".sql")
    try:
        with os.fdopen(fd, "wb") as fh:
            fh.write(resp.content)
        with open(path, "rb") as fh:
            res = subprocess.run(["mysql", "-h", p.db_host, "-P", str(p.db_port), "-u", p.db_user, p.db_name],
                                 stdin=fh, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=600,
                                 env=dict(os.environ, MYSQL_PWD=p.db_pass or ""))
    except (OSError, subprocess.TimeoutExpired) as e:
        rep.fail(T("sql_apply_ko", file=fname, err=short(e)))
        return False
    finally:
        try:
            os.unlink(path)
        except OSError:
            pass
    if res.returncode == 0:
        rep.ok(T("sql_apply_ok", file=fname))
        return True
    rep.fail(T("sql_apply_ko", file=fname, err=res.stderr.decode(errors="replace").strip()[:300]))
    return False


def make_sql_hook(args, interactive):
    state = {"auto_done": False}

    def hook(ck):
        fname = SQL_FILES[ck.glpi_major].rsplit("/", 1)[1]
        has_client = shutil.which("mysql") is not None
        if not interactive:
            if args.apply_sql and not state["auto_done"]:
                state["auto_done"] = True
                if not has_client:
                    ck.rep.fail(T("sql_no_mysql_client"))
                    return False
                apply_sql_file(ck.p, ck.glpi_major, ck.rep)
                return True
            return False
        if not has_client:
            ck.rep.info(T("sql_no_mysql_client"))
        options = ([("auto", T("sql_choice_auto", file=fname))] if has_client else []) + \
                  [("manual", T("sql_choice_manual")), ("skip", T("sql_choice_skip"))]
        print()
        while True:
            choice = ask_choice(T("sql_choice_title"), options, 1 if has_client else 0)
            if choice == "skip":
                return False
            if choice == "manual":
                return True
            if ask_yn(T("sql_confirm_auto", file=fname, db=ck.p.db_name, host=ck.p.db_host), False):
                apply_sql_file(ck.p, ck.glpi_major, ck.rep)
                return True
    return hook


# ─────────────────────────────────────────────────────────────────────────────
# Fix mode: gather parameters and apply
# ─────────────────────────────────────────────────────────────────────────────
def probe_glpi_version(p):
    """Quick look at the GLPI version while prompting, to suggest the right API URL."""
    try:
        conn = db_connect(p.db_host, p.db_port, p.db_user, p.db_pass, p.db_name)
        try:
            rows = db_query(conn, "SELECT value FROM glpi_configs WHERE context='core' AND name='version'")
            views = {r[0] for r in db_query(conn, "SELECT TABLE_NAME FROM information_schema.VIEWS "
                                                  "WHERE TABLE_SCHEMA=%s", (p.db_name,))}
        finally:
            conn.close()
    except DBError as e:
        print(f"    {yellow('[!]')} {T('probe_ko', err=short(e, 120))}")
        return None
    version = rows[0][0] if rows else ""
    m = re.match(r"(\d+)\.", version or "")
    if not m:
        return None
    major = int(m.group(1))
    print(f"    {green('[✓]')} {T('glpi_version_ok', v=version)}")
    if major in SQL_FILES and not set(REQUIRED_VIEWS) <= views:
        print(f"    {yellow('[!]')} {T('hint_apply_sql', url=SQL_FILES[major])}")
    return major


def prompt_params(p):
    p = copy.copy(p)
    print()
    print(bold(T("enter_params")))
    print(dim("  " + T("enter_params_hint")))
    p.url = ask(T("lbl_url"), p.url, validator=v_url).rstrip("/")
    p.db_host = ask(T("lbl_db_host"), p.db_host, validator=v_dbhost)
    p.db_port = int(ask(T("lbl_db_port"), p.db_port or 3306, validator=v_port))
    p.db_name = ask(T("lbl_db_name"), p.db_name or "glpi", validator=v_dbname)
    p.db_user = ask(T("lbl_db_user"), p.db_user)
    p.db_pass = ask(T("lbl_db_pass"), p.db_pass, secret=True, required=False)
    major = probe_glpi_version(p)
    p.readonly = ask_yn(T("lbl_readonly"), p.readonly)
    default_api = p.api_url or (f"{p.url}/apirest.php" if major == 10 else f"{p.url}/api.php/v1")
    p.api_url = ask(T("lbl_api_url"), default_api, validator=v_url).rstrip("/")
    if not p.readonly:
        p.api_user = ask(T("lbl_api_user"), p.api_user)
        p.api_pass = ask(T("lbl_api_pass"), p.api_pass, secret=True)
        found = probe_glpi_tokens(p)
        p.app_token = token_from_glpi("app", found.get("app"), p.app_token, True)
        p.user_token = token_from_glpi("user", found.get("user"), p.user_token, True, p.api_user)
        p.glpi_major = major
        if major == 10:
            print(f"    {cyan('[=]')} {T('cryptkey_glpi10_info', value=CRYPT_KEY_GLPI10)}")
        else:
            print(dim("  " + T("cryptkey_howto")))
            current_key = "" if p.crypt_key == CRYPT_KEY_GLPI10 else p.crypt_key
            p.crypt_key = ask(T("lbl_crypt_key"), current_key, secret=True, validator=v_cryptkey,
                              required=major is not None)
        p.inv_forward = ask_yn(T("lbl_inv_forward"), p.inv_forward)
    elif p.inv_forward:
        print(f"    {cyan('[=]')} {T('forward_disabled_readonly')}")
        p.inv_forward = False
    if p.inv_forward:
        p.inv_forward_url = ask(T("lbl_inv_url"), p.inv_forward_url or f"{p.url}/front/inventory.php",
                                validator=v_url)
        p.inv_plugin = ask_choice(T("lbl_inv_plugin"),
                                  [("glpiinventory", "glpiinventory"), ("fusioninventory", "fusioninventory")],
                                  1 if p.inv_plugin == "fusioninventory" else 0)
        p.inv_agent = ask_choice(T("lbl_inv_agent"),
                                 [("glpiagent", "glpiagent"), ("fusioninventory", "fusioninventory")],
                                 1 if p.inv_agent == "fusioninventory" else 0)
    p.inv_agent_disabled = ask_yn(T("lbl_inv_agent_disabled"), p.inv_agent_disabled)
    return p


def gather_params(args, current, interactive):
    p = copy.copy(current)
    env = os.environ.get
    overrides = {"url": args.url, "db_host": args.db_host, "db_port": args.db_port,
                 "db_name": args.db_name, "db_user": args.db_user,
                 "db_pass": args.db_pass or env("ITSM_DB_PASS"),
                 "api_url": args.api_url, "api_user": args.api_user,
                 "api_pass": args.api_pass or env("ITSM_API_PASS"),
                 "app_token": args.apiapptoken or env("ITSM_APP_TOKEN"),
                 "user_token": args.apiusertoken or env("ITSM_USER_TOKEN"),
                 "crypt_key": args.crypt_key or env("ITSM_CRYPT_KEY"),
                 "readonly": args.readonly, "inv_forward": args.inv_forward,
                 "inv_forward_url": args.inv_forward_url, "inv_plugin": args.inv_plugin,
                 "inv_agent": args.inv_agent, "inv_agent_disabled": args.inv_agent_disabled}
    for key, value in overrides.items():
        if value is not None:
            setattr(p, key, value)
    if args.url:
        p.url = args.url.rstrip("/")
    p.verify_ssl = not args.insecure
    if interactive:
        p = prompt_params(p)
    elif not p.readonly:
        found = probe_glpi_tokens(p)
        p.app_token = token_from_glpi("app", found.get("app"), p.app_token, False)
        p.user_token = token_from_glpi("user", found.get("user"), p.user_token, False, p.api_user)
    return p


def show_plan(p, title_key="plan_title"):
    print()
    print(bold(T(title_key)))
    items = [T("plan_backup"),
             T("plan_update_file", file=GLPI_INI_LOCAL),
             T("plan_federated")]
    if not p.readonly:
        items.append(T("plan_saas"))
    if p.inv_forward:
        items += [T("plan_update_file", file=SUBS_INV_INI + ".local"),
                  T("plan_update_file", file=CLIENT_INV_INI)]
    elif os.path.exists(SUBS_INV_INI + ".local"):
        items.append(T("plan_forward_off", file=SUBS_INV_INI + ".local"))
    items.append(T("plan_update_file", file=SUBS_REG_INI + ".local"))
    if p.readonly or os.path.exists(REGAGENT_INI + ".local"):
        items.append(T("plan_update_file", file=REGAGENT_INI + ".local"))
    items += [T("plan_restart_all", cmd=RESTART_PULSE_SERVICES) if os.access(RESTART_PULSE_SERVICES, os.X_OK)
              else T("plan_restart", list=", ".join(SERVICES)), T("plan_reconf")]
    if p.inv_agent_disabled:
        items.append(T("plan_regen"))
    for item in items:
        print(f"    • {item}")


class Applier:
    def __init__(self, p, rep, interactive, args):
        self.p, self.rep, self.interactive, self.args = p, rep, interactive, args
        self.ts = datetime.datetime.now().strftime("%Y%m%d-%H%M%S")

    def backup(self, path):
        """Copy path to <its directory>/backup/<name>.<timestamp> before any change."""
        if not os.path.exists(path):
            return
        backup_dir = os.path.join(os.path.dirname(path), "backup")
        os.makedirs(backup_dir, mode=0o700, exist_ok=True)  # files contain passwords
        dst = os.path.join(backup_dir, f"{os.path.basename(path)}.{self.ts}")
        shutil.copy2(path, dst)  # keeps the original permissions
        self.rep.ok(T("backup_ok", dst=dst))

    def write_ini(self, path, updates, create=True):
        """updates: {section: {key: value or None (= remove)}}"""
        existed = os.path.exists(path)
        if not existed and not create:
            return
        try:
            cp = new_cp()
            if existed:
                cp.read(path, encoding="utf-8")  # parse errors abort before anything is written
            self.backup(path)
            for section, values in updates.items():
                if not cp.has_section(section):
                    cp.add_section(section)
                for key, value in values.items():
                    if value is None:
                        cp.remove_option(section, key)
                    else:
                        cp.set(section, key, str(value))
            mode = (os.stat(path).st_mode & 0o777) if existed else 0o640
            os.makedirs(os.path.dirname(path), exist_ok=True)
            with open(path, "w", encoding="utf-8") as fh:
                cp.write(fh)
            os.chmod(path, mode)
            self.rep.ok(T("file_written", file=path))
        except (OSError, configparser.Error) as e:
            self.rep.fail(T("write_ko", file=path, err=short(e)))

    def federated(self):
        """On the LOCAL Medulla MariaDB: (re)define the federated server towards the external GLPI.
        Existing local_glpi_* tables are kept: they reference the server by name and follow it.
        Returns False if the server could not be created (the caller then stops)."""
        p, r = self.p, self.rep
        try:
            conn, who = medulla_admin_connect()
        except (DBError, PermissionError) as e:
            r.fail(T("federated_apply_ko", err=short(e)), T("hint_fed_priv"))
            return False
        if who != medulla_db_settings()["user"]:
            r.info(T("fed_using_root"))
        try:
            cur = conn.cursor()
            cur.execute(f"CREATE OR REPLACE SERVER {FEDERATED_SERVER} FOREIGN DATA WRAPPER 'mariadb' OPTIONS ("
                        f"HOST {sql_literal(p.db_host)}, PORT {int(p.db_port)}, USER {sql_literal(p.db_user)}, "
                        f"PASSWORD {sql_literal(p.db_pass)}, DATABASE {sql_literal(p.db_name)})")
            r.ok(T("fedserver_created"))
        except DBError as e:
            r.fail(T("federated_apply_ko", err=short(e)), T("hint_fed_priv"))
            conn.close()
            return False
        try:
            cur.execute("SELECT TABLE_NAME, ENGINE FROM information_schema.TABLES WHERE TABLE_SCHEMA='xmppmaster'")
            existing = {name: engine for name, engine in cur.fetchall() if name in FEDERATED_TABLES}
            kept = [n for n, e in existing.items() if str(e).upper() == "FEDERATED"]
            for n, e in existing.items():
                if str(e).upper() != "FEDERATED":
                    r.warn(T("fedtable_not_federated", table=n, engine=e))
            created = []
            if "local_glpi_machines" in kept and machines_needs_extra_columns():
                cur.execute("SELECT COLUMN_NAME FROM information_schema.COLUMNS WHERE TABLE_SCHEMA='xmppmaster' "
                            "AND TABLE_NAME='local_glpi_machines'")
                cols = {c for (c,) in cur.fetchall()}
                missing_cols = [c for c in MACHINES_EXTRA_COLUMNS if c not in cols]
                if missing_cols:
                    # Same statement as Medulla's update_565_to_566 (a FEDERATED table holds no local data)
                    cur.execute(f"CREATE OR REPLACE TABLE `xmppmaster`.`local_glpi_machines` "
                                f"({federated_columns('local_glpi_machines')}) ENGINE=FEDERATED "
                                f"DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci "
                                f"CONNECTION='{FEDERATED_SERVER}/glpi_computers'")
                    r.ok(T("machines_cols_added", cols=", ".join(missing_cols), v=medulla_version()[1]))
                    kept.remove("local_glpi_machines")
            for name, (remote, _columns) in FEDERATED_TABLES.items():
                if name in existing:
                    continue
                columns = federated_columns(name)
                cur.execute(f"CREATE TABLE IF NOT EXISTS `xmppmaster`.`{name}` ({columns}) ENGINE=FEDERATED "
                            f"DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci "
                            f"CONNECTION='{FEDERATED_SERVER}/{remote}'")
                created.append(name)
            if kept:
                try:  # make sure open handlers reconnect to the new server definition
                    cur.execute("FLUSH TABLES " + ", ".join(f"`xmppmaster`.`{n}`" for n in kept))
                except DBError:
                    pass
                r.ok(T("fedtables_kept", n=len(kept)))
            if created:
                r.ok(T("fedtables_created_list", n=len(created), list=", ".join(created)))
            conn.commit()
            cur.close()
        except DBError as e:
            r.fail(T("federated_apply_ko", err=short(e)))
        finally:
            conn.close()
        return True

    def saas(self):
        """admin.saas_application: API settings. Missing rows are inserted with Medulla's own descriptions."""
        p, r = self.p, self.rep
        try:
            conn = db_connect(database="admin", **medulla_db_settings())
        except DBError as e:
            r.fail(T("saas_update_ko", err=short(e)))
            return
        try:
            cur = conn.cursor()
            cur.execute("SELECT setting_name, setting_value FROM saas_application")
            current = {name: (value or "") for name, value in cur.fetchall()}
            values = {SAAS_KEYS["app_token"]: p.app_token,
                      SAAS_KEYS["user_token"]: p.user_token,
                      SAAS_KEYS["api_url"]: p.api_url}
            # type_api: only filled when empty
            if not current.get("type_api"):
                values["type_api"] = SAAS_TYPE_API
            # crypt key: given value; on GLPI 10 and nothing stored -> REPLACE
            key_name = SAAS_KEYS["crypt_key"]
            if p.crypt_key and not (p.glpi_major != 10 and p.crypt_key == CRYPT_KEY_GLPI10):
                values[key_name] = p.crypt_key
            elif p.glpi_major == 10 and not current.get(key_name):
                values[key_name] = CRYPT_KEY_GLPI10
                p.crypt_key = CRYPT_KEY_GLPI10      # the post-check must see what was written
            for name, value in values.items():
                if name in current:
                    cur.execute("UPDATE saas_application SET setting_value=%s WHERE setting_name=%s", (value, name))
                else:
                    cur.execute("INSERT INTO saas_application (setting_name, setting_value, setting_description) "
                                "VALUES (%s, %s, %s)", (name, value, SAAS_DESCRIPTIONS[name]))
                    r.info(T("saas_row_inserted", name=name))
            conn.commit()
            cur.close()
            r.ok(T("saas_updated"))
        except DBError as e:
            r.fail(T("saas_update_ko", err=short(e)))
        finally:
            conn.close()

    def restart(self):
        r = self.rep
        r.section(T("sec_restart"))
        if os.access(RESTART_PULSE_SERVICES, os.X_OK):
            res = run([RESTART_PULSE_SERVICES], timeout=900)
            if res.returncode == 0:
                r.ok(T("restart_all_ok", cmd=RESTART_PULSE_SERVICES))
                return
            r.warn(T("restart_all_ko", cmd=RESTART_PULSE_SERVICES, err=short(res.stderr or res.returncode, 200)))
        if not shutil.which("systemctl"):
            r.warn(T("tool_missing", tool="systemctl"))
            return
        for svc in SERVICES:
            res = run(["systemctl", "restart", svc], timeout=180)
            if res.returncode == 0:
                r.ok(T("restart_ok", svc=svc))
            else:
                r.fail(T("restart_ko", svc=svc, err=short(res.stderr or res.returncode, 200)),
                       f"journalctl -u {svc} -n 50 --no-pager")

    def reconfigure_agents(self):
        r = self.rep
        sql = "UPDATE machines SET need_reconf=1 WHERE agenttype='machine'"
        try:
            conn = db_connect(database="xmppmaster", **medulla_db_settings())
        except DBError as e:
            r.fail(T("reconf_ko", err=short(e)))
            return
        try:
            count = db_query(conn, "SELECT COUNT(*) FROM machines WHERE agenttype='machine'")[0][0]
            if self.args.no_reconf or (self.interactive and not ask_yn(T("reconf_confirm", n=count), True)):
                r.info(T("reconf_skipped"))
                r.info(f"mysql xmppmaster -e \"{sql}\"")
                return
            cur = conn.cursor()
            cur.execute(sql)
            conn.commit()
            r.ok(T("reconf_ok", n=count))
            cur.close()
        except DBError as e:
            r.fail(T("reconf_ko", err=short(e)))
        finally:
            conn.close()

    def regenerate_agent(self):
        r = self.rep
        r.section(T("sec_regen"))
        if not os.path.isfile(GEN_AGENT):
            r.fail(T("file_missing", file=GEN_AGENT))
            return
        self.backup(GEN_OPTIONS)
        try:
            with open(GEN_AGENT_LOG, "w") as log:
                rc = subprocess.run([GEN_AGENT, "--disable-inventory"], stdout=log,
                                    stderr=subprocess.STDOUT).returncode
        except OSError as e:
            rc = short(e)
        if rc == 0:
            r.ok(T("regen_ok"))
        else:
            r.fail(T("regen_ko", rc=rc, log=GEN_AGENT_LOG))

    def run(self):
        p = self.p
        self.rep.section(T("sec_apply"))
        if not self.federated():
            self.rep.fail(T("apply_stopped"))
            return
        dbsec = {"glpi_dbhost": p.db_host, "glpi_dbport": p.db_port, "glpi_dbuser": p.db_user,
                 "glpi_dbpasswd": p.db_pass, "glpi_dbname": p.db_name}
        webservices = {"purge_machine": "1", "glpi_base_url": p.api_url}
        if not p.readonly:
            webservices.update(glpi_username=p.api_user, glpi_password=p.api_pass)
        self.write_ini(GLPI_INI_LOCAL, {
            "main": {"disable": "0", "dbhost": p.db_host, "dbport": p.db_port, "dbname": p.db_name,
                     "dbuser": p.db_user, "dbpasswd": p.db_pass,
                     "glpi_computer_uri": f"{p.url}/front/computer.form.php?id=",
                     "dbreadonly": "1" if p.readonly else None},
            "webservices": webservices,
            "authentication_glpi": {"baseurl": p.url, "doauth": "1"}})
        if not p.readonly:
            self.saas()
        if p.inv_forward:
            self.write_ini(SUBS_INV_INI + ".local", {
                "glpi": {"enable_forward": "True", "url_to_forward": p.inv_forward_url,
                         "inventory_plugin": p.inv_plugin},
                "glpidatabase": dbsec})
            self.write_ini(CLIENT_INV_INI, {
                "parameters": {"agent": "glpiagent" if p.inv_agent == "glpiagent" else None}})
        else:
            self.write_ini(SUBS_INV_INI + ".local", {"glpi": {"enable_forward": "False"}}, create=False)
        self.write_ini(SUBS_REG_INI + ".local", {"glpidatabase": dbsec})
        self.write_ini(REGAGENT_INI + ".local",
                       {"parameters": {"check_uuidinventory": "True" if p.readonly else None}},
                       create=p.readonly)
        self.restart()
        self.reconfigure_agents()
        if p.inv_agent_disabled:
            self.regenerate_agent()


# ─────────────────────────────────────────────────────────────────────────────
# Modes
# ─────────────────────────────────────────────────────────────────────────────
def mode_check(args, interactive):
    rep = Report()
    ck = Checker(Params(), rep)
    if not ck.check_prerequisites(require_root=False):
        return rep.summary()
    ck.check_medulla_db()
    connected, host, _, _ = external_glpi_state()
    if not connected:
        rep.summary()
        print()
        box([T("not_connected_title"), "",
             T("not_connected_body", file=GLPI_INI_LOCAL, host=host or T("not_set")),
             T("not_connected_next")])
        if interactive and ask_yn(T("offer_connect"), True):
            return mode_fix(args, interactive)
        return 3
    p, err = load_current_params()
    p.verify_ssl = not args.insecure
    ck.p = p
    rep.section(T("sec_params"))
    rep.info(T("params_from_config"))
    if err:
        rep.warn(T("saas_read_ko", err=err))
    validate_params(p, rep)
    ck.run_remote()
    ck.run_local()
    ck.close()
    rc = rep.summary()
    if interactive and rep.failed:
        print_fix_preview(rep, p, ck.glpi_major)
        if ask_yn(T("offer_fix"), False):
            return mode_fix(args, interactive)
    return rc


def print_fix_preview(rep, p, glpi_major):
    """Before offering fix mode: what it would change, and which failures that covers."""
    groups = rep.failures_by_fix()
    sql_file = SQL_FILES[glpi_major].rsplit("/", 1)[1] if glpi_major in SQL_FILES else "glpi-100.sql / glpi-110.sql"
    print()
    print(bold(T("preview_title")))
    show_plan(p, "preview_plan")
    for cat, title in (("auto", T("fixcat_auto")),
                       ("params", T("fixcat_params")),
                       ("sql", T("fixcat_sql", file=sql_file)),
                       ("manual", T("fixcat_manual"))):
        if not groups[cat]:
            continue
        color = red if cat == "manual" else green
        print()
        print(bold("  " + title))
        for msg in groups[cat]:
            print(f"   {color('•')} {msg}")
    print()
    print(dim("  " + T("preview_note")))
    print()


def mode_fix(args, interactive):
    rep = Report()
    ck = Checker(Params(), rep)
    if not ck.check_prerequisites(require_root=True) or not ck.check_medulla_db() or rep.failed:
        rep.summary()
        return 1
    connected, _, _, _ = external_glpi_state()
    if connected:
        current, _ = load_current_params()
    else:
        # dbhost = localhost: Medulla still uses its local GLPI. Its values (localhost, local
        # credentials, local API tokens) must not be offered as defaults for the external one.
        current = Params()
        print()
        box([T("connect_new_title"), "", T("connect_new_body")])
    p = gather_params(args, current, interactive)
    if v_dbhost(p.db_host or ""):
        # Never write dbhost = localhost: that would mean "no external GLPI", even with --force
        print(red("  [✗] " + v_dbhost(p.db_host)))
        print(red("  " + T("abort_preflight_failed").split(":")[0].rstrip() + "."))
        return 2

    # Pre-flight: validate the entered parameters against the external GLPI
    while True:
        pre = Report()
        ck = Checker(p, pre)
        print()
        print(bold(T("preflight_title")))
        if validate_params(p, pre):
            ck.run_remote(sql_hook=make_sql_hook(args, interactive))
        ck.close()
        pre.summary(T("preflight_summary"))
        if pre.failed == 0:
            break
        if not interactive:
            if args.force:
                print(yellow(T("force_continue")))
                break
            print(red(T("abort_preflight_failed")))
            return 1
        choice = ask_choice(T("preflight_failed_choice"),
                            [("edit", T("choice_edit")), ("force", T("choice_force")),
                             ("abort", T("choice_abort"))], 0)
        if choice == "edit":
            p = prompt_params(p)
            continue
        if choice == "abort":
            print(T("aborted"))
            return 2
        break

    show_plan(p)
    if interactive and not ask_yn(T("confirm_apply"), False):
        print(T("aborted"))
        return 2
    applied = Report()
    Applier(p, applied, interactive, args).run()

    time.sleep(3)  # let the services start before checking them
    print()
    print(bold(T("postcheck_title")))
    post = Report()
    ck = Checker(p, post)
    ck.check_medulla_db()
    ck.run_remote()
    ck.run_local()
    ck.close()
    rc = post.summary()
    if applied.failed:
        print(red("  " + T("apply_had_failures", n=applied.failed)))
        rc = 1
    return rc


def choose_language(default):
    names = [("en", "English"), ("fr", "Français"), ("es", "Español"), ("de", "Deutsch")]
    print(bold("Language / Langue / Idioma / Sprache"))
    for i, (_, name) in enumerate(names, 1):
        print(f"  {i}) {name}")
    while True:
        val = input(f"  > [{LANGS.index(default) + 1}] ").strip().lower()
        if not val:
            return default
        if val.isdigit() and 1 <= int(val) <= len(names):
            return names[int(val) - 1][0]
        if val in LANGS:
            return val


def build_parser():
    ap = argparse.ArgumentParser(description="Check / configure the connection between Medulla and an "
                                             "external GLPI (ITSM).")
    ap.add_argument("--lang", choices=LANGS, help="Interface language (default: from $LANG)")
    ap.add_argument("--mode", choices=("check", "fix"), help="check = diagnostics only, fix = configure")
    ap.add_argument("--non-interactive", action="store_true", help="Never prompt (for automation)")
    ap.add_argument("--insecure", action="store_true", help="Do not verify TLS certificates")
    ap.add_argument("--force", action="store_true", help="fix: apply even if pre-flight checks fail")
    ap.add_argument("--apply-sql", action="store_true",
                    help="fix: download and apply glpi-100.sql / glpi-110.sql when the views are missing")
    ap.add_argument("--no-reconf", action="store_true", help="fix: do not mark agents for reconfiguration")
    g = ap.add_argument_group("GLPI parameters (fix mode, same names as change_itsm_parameters.py)")
    g.add_argument("--url", help="GLPI web URL")
    g.add_argument("--db-host")
    g.add_argument("--db-port", type=int)
    g.add_argument("--db-name")
    g.add_argument("--db-user")
    g.add_argument("--db-pass", help="or ITSM_DB_PASS")
    g.add_argument("--api-url", help="GLPI 10: https://<server>/apirest.php - GLPI 11: https://<server>/api.php/v1")
    g.add_argument("--api-user")
    g.add_argument("--api-pass", help="or ITSM_API_PASS")
    g.add_argument("--readonly", type=str_to_bool)
    g.add_argument("--crypt-key", help="base64 of glpicrypt.key, or ITSM_CRYPT_KEY")
    g.add_argument("--apiapptoken", help="or ITSM_APP_TOKEN")
    g.add_argument("--apiusertoken", help="or ITSM_USER_TOKEN")
    g.add_argument("--inv-forward", type=str_to_bool)
    g.add_argument("--inv-forward-url", help="e.g. https://<server>/front/inventory.php")
    g.add_argument("--inv-plugin", choices=("glpiinventory", "fusioninventory"))
    g.add_argument("--inv-agent", choices=("glpiagent", "fusioninventory"))
    g.add_argument("--inv-agent-disabled", type=str_to_bool)
    return ap


def main():
    global LANG
    args = build_parser().parse_args()
    interactive = not args.non_interactive and sys.stdin.isatty()
    try:
        LANG = args.lang or (choose_language(detect_lang()) if interactive else detect_lang())
        print()
        print(bold(f"Medulla ⇄ GLPI — {T('banner')}"))
        mode = args.mode
        if not mode:
            print()
            connected = print_glpi_state()
            print()
            if not interactive:
                mode = "check"
            elif connected:
                mode = ask_choice(T("menu_title"), [("check", T("menu_check")), ("fix", T("menu_fix")),
                                                    ("quit", T("menu_quit"))], 0)
            else:
                mode = ask_choice(T("menu_title"), [("fix", T("menu_connect")), ("check", T("menu_check")),
                                                    ("quit", T("menu_quit"))], 0)
        if mode == "quit":
            return 0
        return mode_check(args, interactive) if mode == "check" else mode_fix(args, interactive)
    except (KeyboardInterrupt, EOFError):
        print()
        print(T("aborted"))
        return 2


# ─────────────────────────────────────────────────────────────────────────────
# Messages: (en, fr, es, de) — a single-element tuple is used for every language
# ─────────────────────────────────────────────────────────────────────────────
MSG = {
    # UI
    "banner": ("external ITSM (GLPI) connection tool", "outil de connexion à un ITSM (GLPI) externe",
               "herramienta de conexión a un ITSM (GLPI) externo", "Werkzeug zur Anbindung eines externen ITSM (GLPI)"),
    "menu_title": ("What do you want to do?", "Que voulez-vous faire ?", "¿Qué desea hacer?", "Was möchten Sie tun?"),
    "menu_check": ("Check mode — diagnose the current configuration (no change)",
                   "Mode vérification — diagnostiquer la configuration actuelle (aucune modification)",
                   "Modo verificación — diagnosticar la configuración actual (sin cambios)",
                   "Prüfmodus — aktuelle Konfiguration diagnostizieren (keine Änderung)"),
    "menu_fix": ("Fix mode — configure / repair the connection to an external GLPI",
                 "Mode correction — configurer / réparer la connexion à un GLPI externe",
                 "Modo corrección — configurar / reparar la conexión a un GLPI externo",
                 "Korrekturmodus — Verbindung zu einem externen GLPI einrichten / reparieren"),
    "menu_connect": ("Connect an external GLPI to Medulla (asks for all needed parameters)",
                     "Connecter un GLPI externe à Medulla (pose toutes les questions nécessaires)",
                     "Conectar un GLPI externo a Medulla (pregunta todos los parámetros necesarios)",
                     "Ein externes GLPI mit Medulla verbinden (fragt alle nötigen Parameter ab)"),
    "state_connected": ("External GLPI connected: {host}:{port}/{db}", "GLPI externe connecté : {host}:{port}/{db}",
                        "GLPI externo conectado: {host}:{port}/{db}", "Externes GLPI verbunden: {host}:{port}/{db}"),
    "state_not_connected": ("No external GLPI connected (dbhost = {host} in {file})",
                            "Aucun GLPI externe connecté (dbhost = {host} dans {file})",
                            "Ningún GLPI externo conectado (dbhost = {host} en {file})",
                            "Kein externes GLPI verbunden (dbhost = {host} in {file})"),
    "not_connected_title": ("No external GLPI is connected to Medulla", "Aucun GLPI externe n'est connecté à Medulla",
                            "Ningún GLPI externo está conectado a Medulla", "Kein externes GLPI ist mit Medulla verbunden"),
    "not_connected_body": ("[main] dbhost = {host} in {file}: Medulla uses its local GLPI.",
                           "[main] dbhost = {host} dans {file} : Medulla utilise son GLPI local.",
                           "[main] dbhost = {host} en {file}: Medulla usa su GLPI local.",
                           "[main] dbhost = {host} in {file}: Medulla nutzt sein lokales GLPI."),
    "not_connected_next": ("The external GLPI checks are skipped: run the configuration first.",
                           "Les vérifications du GLPI externe sont ignorées : lancez d'abord la configuration.",
                           "Las verificaciones del GLPI externo se omiten: ejecute primero la configuración.",
                           "Die Prüfungen des externen GLPI entfallen: zuerst die Konfiguration ausführen."),
    "offer_connect": ("Connect an external GLPI now?", "Connecter un GLPI externe maintenant ?",
                      "¿Conectar un GLPI externo ahora?", "Jetzt ein externes GLPI verbinden?"),
    "connect_new_title": ("New external GLPI connection", "Nouvelle connexion à un GLPI externe",
                          "Nueva conexión a un GLPI externo", "Neue Verbindung zu einem externen GLPI"),
    "connect_new_body": ("Medulla currently uses its local GLPI: no current value is reused.",
                         "Medulla utilise actuellement son GLPI local : aucune valeur actuelle n'est reprise.",
                         "Medulla usa actualmente su GLPI local: no se reutiliza ningún valor actual.",
                         "Medulla nutzt derzeit sein lokales GLPI: keine aktuellen Werte werden übernommen."),
    "dbhost_localhost": ("localhost is the local GLPI: enter the host of the external GLPI database",
                         "localhost désigne le GLPI local : saisissez l'hôte de la base du GLPI externe",
                         "localhost es el GLPI local: introduzca el host de la BD del GLPI externo",
                         "localhost ist das lokale GLPI: Host der externen GLPI-Datenbank eingeben"),
    "menu_quit": ("Quit", "Quitter", "Salir", "Beenden"),
    "aborted": ("Aborted.", "Abandon.", "Cancelado.", "Abgebrochen."),
    "yes": ("yes", "oui", "sí", "ja"),
    "no": ("no", "non", "no", "nein"),
    "not_set": ("(not set)", "(non défini)", "(no definido)", "(nicht gesetzt)"),
    "keep_current": ("Enter = keep current", "Entrée = conserver", "Intro = conservar", "Enter = beibehalten"),
    "yn_default_yes": ("[Y/n]", "[O/n]", "[S/n]", "[J/n]"),
    "yn_default_no": ("[y/N]", "[o/N]", "[s/N]", "[j/N]"),
    "yn_invalid": ("Please answer yes or no.", "Répondez par oui ou non.", "Responda sí o no.",
                   "Bitte mit ja oder nein antworten."),
    "choice_invalid": ("Invalid choice.", "Choix invalide.", "Opción no válida.", "Ungültige Auswahl."),
    "value_required": ("A value is required.", "Une valeur est requise.", "Se requiere un valor.",
                       "Ein Wert ist erforderlich."),
    "invalid_url": ("Invalid URL (expected http(s)://…)", "URL invalide (attendu : http(s)://…)",
                    "URL no válida (se espera http(s)://…)", "Ungültige URL (erwartet: http(s)://…)"),
    "invalid_port": ("Invalid port (1-65535)", "Port invalide (1-65535)", "Puerto no válido (1-65535)",
                     "Ungültiger Port (1-65535)"),
    "invalid_dbname": ("Invalid database name", "Nom de base invalide", "Nombre de base de datos no válido",
                       "Ungültiger Datenbankname"),
    "enter_params": ("External GLPI connection parameters", "Paramètres de connexion au GLPI externe",
                     "Parámetros de conexión al GLPI externo", "Verbindungsparameter des externen GLPI"),
    "enter_params_hint": ("The value in brackets is the one offered: press Enter to keep it.",
                          "La valeur entre crochets est celle proposée : Entrée pour la conserver.",
                          "El valor entre corchetes es el propuesto: pulse Intro para conservarlo.",
                          "Der Wert in Klammern ist der vorgeschlagene: Enter drücken, um ihn zu behalten."),
    "probe_ko": ("Cannot query GLPI yet ({err}) — continuing, the full check follows.",
                 "Impossible d'interroger GLPI pour l'instant ({err}) — on continue, la vérification complète suivra.",
                 "No se puede consultar GLPI por ahora ({err}) — se continúa, la verificación completa vendrá después.",
                 "GLPI kann noch nicht abgefragt werden ({err}) — es geht weiter, die vollständige Prüfung folgt."),
    "forward_disabled_readonly": ("Read-only mode: inventory forwarding is disabled.",
                                  "Mode lecture seule : la remontée d'inventaire est désactivée.",
                                  "Modo solo lectura: el reenvío de inventario se desactiva.",
                                  "Nur-Lese-Modus: die Inventarweiterleitung wird deaktiviert."),
    "cryptkey_howto": ("On the GLPI server: base64 -w0 /etc/glpi/glpicrypt.key (or <glpi>/config/glpicrypt.key)",
                       "Sur le serveur GLPI : base64 -w0 /etc/glpi/glpicrypt.key (ou <glpi>/config/glpicrypt.key)",
                       "En el servidor GLPI: base64 -w0 /etc/glpi/glpicrypt.key (o <glpi>/config/glpicrypt.key)",
                       "Auf dem GLPI-Server: base64 -w0 /etc/glpi/glpicrypt.key (oder <glpi>/config/glpicrypt.key)"),
    "offer_fix": ("Some checks failed. Start fix mode now?",
                  "Des vérifications ont échoué. Lancer le mode correction maintenant ?",
                  "Algunas verificaciones fallaron. ¿Iniciar el modo corrección ahora?",
                  "Einige Prüfungen sind fehlgeschlagen. Korrekturmodus jetzt starten?"),
    "preview_title": ("What fix mode would do", "Ce que ferait le mode correction",
                      "Lo que haría el modo corrección", "Was der Korrekturmodus tun würde"),
    "preview_plan": ("Planned changes:", "Modifications prévues :", "Cambios previstos:", "Geplante Änderungen:"),
    "fixcat_auto": ("Failures fixed by these changes:", "Échecs corrigés par ces modifications :",
                    "Fallos corregidos por estos cambios:", "Durch diese Änderungen behobene Fehler:"),
    "fixcat_params": ("Failures fixed by re-entering a parameter (fix mode will ask for them):",
                      "Échecs corrigés en ressaisissant un paramètre (le mode correction vous les demandera) :",
                      "Fallos corregidos volviendo a introducir un parámetro (el modo corrección los pedirá):",
                      "Fehler, die durch erneute Eingabe eines Parameters behoben werden (der Korrekturmodus fragt danach):"),
    "fixcat_sql": ("Failures fixed by applying {file} (fix mode will offer to do it):",
                   "Échecs corrigés en appliquant {file} (le mode correction proposera de le faire) :",
                   "Fallos corregidos aplicando {file} (el modo corrección propondrá hacerlo):",
                   "Fehler, die durch Anwenden von {file} behoben werden (der Korrekturmodus bietet es an):"),
    "fixcat_manual": ("Failures the script cannot fix (manual action required, see the hints above):",
                      "Échecs que le script ne peut pas corriger (action manuelle requise, voir les indications plus haut) :",
                      "Fallos que el script no puede corregir (se requiere acción manual, ver indicaciones arriba):",
                      "Fehler, die das Skript nicht beheben kann (manueller Eingriff nötig, siehe Hinweise oben):"),
    "preview_note": ("Current values are offered as defaults; every change is confirmed before being applied, "
                     "and modified files are saved into backup/.",
                     "Les valeurs actuelles sont proposées par défaut ; chaque modification est confirmée avant "
                     "application et les fichiers modifiés sont sauvegardés dans backup/.",
                     "Los valores actuales se proponen por defecto; cada cambio se confirma antes de aplicarse "
                     "y los archivos modificados se guardan en backup/.",
                     "Die aktuellen Werte werden vorgeschlagen; jede Änderung wird vor dem Anwenden bestätigt "
                     "und geänderte Dateien werden in backup/ gesichert."),
    "params_from_config": ("Parameters read from the current Medulla configuration:",
                           "Paramètres lus dans la configuration Medulla actuelle :",
                           "Parámetros leídos de la configuración actual de Medulla:",
                           "Aus der aktuellen Medulla-Konfiguration gelesene Parameter:"),

    # Labels
    "lbl_url": ("GLPI web URL", "URL web de GLPI", "URL web de GLPI", "GLPI-Web-URL"),
    "lbl_db_host": ("GLPI DB host", "Hôte de la base GLPI", "Host de la BD de GLPI", "GLPI-DB-Host"),
    "lbl_db_port": ("GLPI DB port", "Port de la base GLPI", "Puerto de la BD de GLPI", "GLPI-DB-Port"),
    "lbl_db_name": ("GLPI DB name", "Nom de la base GLPI", "Nombre de la BD de GLPI", "GLPI-DB-Name"),
    "lbl_db_user": ("GLPI DB user", "Utilisateur de la base GLPI", "Usuario de la BD de GLPI", "GLPI-DB-Benutzer"),
    "lbl_db_pass": ("GLPI DB password", "Mot de passe de la base GLPI", "Contraseña de la BD de GLPI",
                    "GLPI-DB-Passwort"),
    "lbl_readonly": ("Read-only GLPI database for Medulla?", "Base GLPI en lecture seule pour Medulla ?",
                     "¿BD de GLPI en solo lectura para Medulla?", "GLPI-Datenbank für Medulla nur lesend?"),
    "lbl_api_url": ("GLPI API URL", "URL de l'API GLPI", "URL de la API de GLPI", "GLPI-API-URL"),
    "lbl_api_user": ("API user", "Utilisateur API", "Usuario API", "API-Benutzer"),
    "lbl_api_pass": ("API password", "Mot de passe API", "Contraseña API", "API-Passwort"),
    "lbl_app_token": ("API application token (App-Token)", "Jeton d'application API (App-Token)",
                      "Token de aplicación API (App-Token)", "API-Anwendungstoken (App-Token)"),
    "lbl_user_token": ("API user token", "Jeton utilisateur API", "Token de usuario API", "API-Benutzertoken"),
    "lbl_crypt_key": ("GLPI crypt key (base64)", "Clé de chiffrement GLPI (base64)",
                      "Clave de cifrado de GLPI (base64)", "GLPI-Schlüssel (base64)"),
    "lbl_inv_forward": ("Forward inventories to GLPI?", "Remonter les inventaires vers GLPI ?",
                        "¿Reenviar los inventarios a GLPI?", "Inventare an GLPI weiterleiten?"),
    "lbl_inv_url": ("Inventory forward URL", "URL de remontée d'inventaire", "URL de reenvío de inventario",
                    "URL für die Inventarweiterleitung"),
    "lbl_inv_plugin": ("GLPI inventory plugin", "Plugin d'inventaire GLPI", "Plugin de inventario de GLPI",
                       "GLPI-Inventar-Plugin"),
    "lbl_inv_agent": ("Inventory agent on clients", "Agent d'inventaire sur les postes",
                      "Agente de inventario en los equipos", "Inventar-Agent auf den Clients"),
    "lbl_inv_agent_disabled": ("Disable the inventory agent in the Medulla agent (regenerates the installer)?",
                               "Désactiver l'agent d'inventaire dans l'agent Medulla (régénère l'installeur) ?",
                               "¿Desactivar el agente de inventario en el agente Medulla (regenera el instalador)?",
                               "Inventar-Agent im Medulla-Agenten deaktivieren (Installer wird neu erzeugt)?"),
    "lbl_verify_ssl": ("TLS certificate verification", "Vérification des certificats TLS",
                       "Verificación de certificados TLS", "TLS-Zertifikatsprüfung"),

    # Sections
    "sec_prereq": ("Prerequisites", "Prérequis", "Requisitos previos", "Voraussetzungen"),
    "sec_medulla_db": ("Medulla database", "Base de données Medulla", "Base de datos de Medulla",
                       "Medulla-Datenbank"),
    "sec_params": ("Parameters", "Paramètres", "Parámetros", "Parameter"),
    "sec_network": ("Network access to the GLPI database", "Accès réseau à la base GLPI",
                    "Acceso de red a la BD de GLPI", "Netzwerkzugriff auf die GLPI-Datenbank"),
    "sec_glpi_db": ("GLPI database connection", "Connexion à la base GLPI", "Conexión a la BD de GLPI",
                    "Verbindung zur GLPI-Datenbank"),
    "sec_version": ("GLPI version", "Version de GLPI", "Versión de GLPI", "GLPI-Version"),
    "sec_schema": ("Required tables and views", "Tables et vues requises", "Tablas y vistas requeridas",
                   "Erforderliche Tabellen und Views"),
    "sec_privileges": ("Database privileges", "Droits sur la base", "Privilegios en la base de datos",
                       "Datenbankrechte"),
    "sec_plugins": ("GLPI inventory plugins", "Plugins d'inventaire GLPI", "Plugins de inventario de GLPI",
                    "GLPI-Inventar-Plugins"),
    "sec_settings": ("GLPI settings", "Paramétrage GLPI", "Configuración de GLPI", "GLPI-Einstellungen"),
    "sec_api_objects": ("GLPI API client and user", "Client et utilisateur API GLPI",
                        "Cliente y usuario API de GLPI", "GLPI-API-Client und -Benutzer"),
    "sec_cryptkey": ("GLPI crypt key", "Clé de chiffrement GLPI", "Clave de cifrado de GLPI", "GLPI-Schlüssel"),
    "sec_web": ("GLPI web access", "Accès web GLPI", "Acceso web a GLPI", "GLPI-Webzugriff"),
    "sec_api": ("GLPI REST API", "API REST GLPI", "API REST de GLPI", "GLPI-REST-API"),
    "sec_forward": ("Inventory forwarding", "Remontée d'inventaire", "Reenvío de inventario",
                    "Inventarweiterleitung"),
    "sec_medulla_conf": ("Medulla configuration files", "Fichiers de configuration Medulla",
                         "Archivos de configuración de Medulla", "Medulla-Konfigurationsdateien"),
    "sec_federated": ("Federated tables (Medulla → GLPI)", "Tables fédérées (Medulla → GLPI)",
                      "Tablas federadas (Medulla → GLPI)", "Föderierte Tabellen (Medulla → GLPI)"),
    "sec_services": ("Medulla services", "Services Medulla", "Servicios de Medulla", "Medulla-Dienste"),
    "sec_apply": ("Applying the configuration", "Application de la configuration",
                  "Aplicación de la configuración", "Konfiguration wird angewendet"),
    "sec_restart": ("Restarting services", "Redémarrage des services", "Reinicio de los servicios",
                    "Dienste werden neu gestartet"),
    "sec_regen": ("Medulla agent regeneration", "Régénération de l'agent Medulla",
                  "Regeneración del agente Medulla", "Neuerstellung des Medulla-Agenten"),

    # Prerequisites
    "python_too_old": ("Python {v} is too old (3.7+ required)", "Python {v} est trop ancien (3.7+ requis)",
                       "Python {v} es demasiado antiguo (se requiere 3.7+)",
                       "Python {v} ist zu alt (3.7+ erforderlich)"),
    "module_ok": ("Python module {mod} available", "Module Python {mod} disponible",
                  "Módulo Python {mod} disponible", "Python-Modul {mod} verfügbar"),
    "module_missing": ("Python module {mod} is missing", "Module Python {mod} manquant",
                       "Falta el módulo Python {mod}", "Python-Modul {mod} fehlt"),
    "hint_apt": ("apt install {pkg}",),
    "nacl_missing": ("Python module nacl missing: the crypt key cannot be validated against GLPI data",
                     "Module Python nacl absent : la clé de chiffrement ne pourra pas être validée sur les données GLPI",
                     "Falta el módulo Python nacl: la clave de cifrado no podrá validarse con los datos de GLPI",
                     "Python-Modul nacl fehlt: der Schlüssel kann nicht anhand der GLPI-Daten geprüft werden"),
    "root_ok": ("Running as root", "Exécution en root", "Ejecución como root", "Ausführung als root"),
    "root_required": ("Fix mode must be run as root", "Le mode correction doit être lancé en root",
                      "El modo corrección debe ejecutarse como root",
                      "Der Korrekturmodus muss als root ausgeführt werden"),
    "root_recommended": ("Not running as root: some files may be unreadable",
                         "Pas en root : certains fichiers peuvent être illisibles",
                         "No se ejecuta como root: algunos archivos pueden no ser legibles",
                         "Nicht als root: einige Dateien sind evtl. nicht lesbar"),
    "tool_ok": ("Command {tool} available", "Commande {tool} disponible", "Comando {tool} disponible",
                "Befehl {tool} verfügbar"),
    "tool_missing": ("Command {tool} not found", "Commande {tool} introuvable", "Comando {tool} no encontrado",
                     "Befehl {tool} nicht gefunden"),

    # Medulla database
    "medulla_db_target": ("Medulla DB: {user}@{host}:{port}",),
    "medulla_db_ok": ("Connected to the Medulla database (xmppmaster)",
                      "Connexion à la base Medulla (xmppmaster) réussie",
                      "Conexión a la BD de Medulla (xmppmaster) correcta",
                      "Verbindung zur Medulla-Datenbank (xmppmaster) erfolgreich"),
    "medulla_db_ko": ("Cannot connect to the Medulla database: {err}",
                      "Connexion impossible à la base Medulla : {err}",
                      "No se puede conectar a la BD de Medulla: {err}",
                      "Keine Verbindung zur Medulla-Datenbank: {err}"),
    "hint_check_file": ("Check {file}", "Vérifiez {file}", "Revise {file}", "Prüfen Sie {file}"),
    "federated_engine_ok": ("FEDERATED storage engine enabled on the Medulla MariaDB",
                            "Moteur FEDERATED actif sur le MariaDB de Medulla",
                            "Motor FEDERATED activo en el MariaDB de Medulla",
                            "FEDERATED-Engine im MariaDB von Medulla aktiv"),
    "federated_engine_ko": ("FEDERATED storage engine not enabled on the Medulla MariaDB",
                            "Moteur FEDERATED non actif sur le MariaDB de Medulla",
                            "Motor FEDERATED no activo en el MariaDB de Medulla",
                            "FEDERATED-Engine im MariaDB von Medulla nicht aktiv"),
    "hint_federated_engine1": ("Enable it on the Medulla MariaDB server:",
                               "Activez-le sur le serveur MariaDB de Medulla :",
                               "Actívelo en el servidor MariaDB de Medulla:",
                               "Auf dem MariaDB-Server von Medulla aktivieren:"),
    "hint_federated_engine2": ("then add plugin_load_add = ha_federatedx in the [mariadb] section to make it permanent",
                               "puis ajoutez plugin_load_add = ha_federatedx dans la section [mariadb] pour le rendre permanent",
                               "y añada plugin_load_add = ha_federatedx en la sección [mariadb] para hacerlo permanente",
                               "und plugin_load_add = ha_federatedx im Abschnitt [mariadb] eintragen, damit es dauerhaft ist"),
    "admin_db_ok": ("Table admin.saas_application readable", "Table admin.saas_application lisible",
                    "Tabla admin.saas_application legible", "Tabelle admin.saas_application lesbar"),
    "admin_db_ko": ("Table admin.saas_application unreadable: {err}", "Table admin.saas_application illisible : {err}",
                    "Tabla admin.saas_application no legible: {err}", "Tabelle admin.saas_application nicht lesbar: {err}"),

    # Parameters
    "params_complete": ("All required parameters are set", "Tous les paramètres requis sont renseignés",
                        "Todos los parámetros requeridos están definidos", "Alle erforderlichen Parameter sind gesetzt"),
    "param_missing": ("Missing parameter(s): {name}", "Paramètre(s) manquant(s) : {name}",
                      "Parámetro(s) faltante(s): {name}", "Fehlende(r) Parameter: {name}"),
    "readonly_forward_conflict": ("Inconsistent: inventory forwarding requires write access (read-only mode is enabled)",
                                  "Incohérent : la remontée d'inventaire nécessite un accès en écriture (mode lecture seule activé)",
                                  "Incoherente: el reenvío de inventario requiere acceso de escritura (modo solo lectura activado)",
                                  "Widersprüchlich: Inventarweiterleitung erfordert Schreibzugriff (Nur-Lese-Modus aktiv)"),
    "saas_read_ko": ("Cannot read API settings from admin.saas_application: {err}",
                     "Lecture impossible des paramètres API dans admin.saas_application : {err}",
                     "No se pueden leer los parámetros API de admin.saas_application: {err}",
                     "API-Einstellungen aus admin.saas_application nicht lesbar: {err}"),
    "file_missing": ("File not found: {file}", "Fichier introuvable : {file}", "Archivo no encontrado: {file}",
                     "Datei nicht gefunden: {file}"),

    # Network
    "dns_ok": ("{host} resolves to {ip}", "{host} résout en {ip}", "{host} se resuelve como {ip}",
               "{host} wird zu {ip} aufgelöst"),
    "dns_ko": ("Cannot resolve {host}: {err}", "Résolution DNS impossible pour {host} : {err}",
               "No se puede resolver {host}: {err}", "{host} kann nicht aufgelöst werden: {err}"),
    "source_ip": ("Medulla source IP towards GLPI: {ip}", "IP source de Medulla vers GLPI : {ip}",
                  "IP de origen de Medulla hacia GLPI: {ip}", "Quell-IP von Medulla Richtung GLPI: {ip}"),
    "tcp_ok": ("TCP port {port} open on {host}", "Port TCP {port} ouvert sur {host}",
               "Puerto TCP {port} abierto en {host}", "TCP-Port {port} auf {host} offen"),
    "tcp_ko": ("TCP port {port} unreachable on {host}: {err}", "Port TCP {port} injoignable sur {host} : {err}",
               "Puerto TCP {port} inaccesible en {host}: {err}", "TCP-Port {port} auf {host} nicht erreichbar: {err}"),
    "hint_bind_address": ("On the GLPI DB server, check bind-address (e.g. /etc/mysql/mariadb.conf.d/50-server.cnf)",
                          "Sur le serveur de base GLPI, vérifiez bind-address (ex. /etc/mysql/mariadb.conf.d/50-server.cnf)",
                          "En el servidor de BD de GLPI, revise bind-address (p. ej. /etc/mysql/mariadb.conf.d/50-server.cnf)",
                          "Auf dem GLPI-DB-Server bind-address prüfen (z. B. /etc/mysql/mariadb.conf.d/50-server.cnf)"),
    "hint_firewall": ("Check the firewalls: {ip} must reach port {port}",
                      "Vérifiez les pare-feux : {ip} doit pouvoir joindre le port {port}",
                      "Revise los cortafuegos: {ip} debe poder alcanzar el puerto {port}",
                      "Firewalls prüfen: {ip} muss Port {port} erreichen können"),
    "hint_dns": ("Check the host name / DNS resolution", "Vérifiez le nom d'hôte / la résolution DNS",
                 "Revise el nombre de host / la resolución DNS", "Hostnamen / DNS-Auflösung prüfen"),
    "skip_db_checks": ("GLPI database checks skipped", "Vérifications de la base GLPI ignorées",
                       "Verificaciones de la BD de GLPI omitidas", "GLPI-Datenbankprüfungen übersprungen"),

    # GLPI database
    "glpi_db_ok": ("Connected as {user} to {host}:{port}", "Connecté en tant que {user} à {host}:{port}",
                   "Conectado como {user} a {host}:{port}", "Als {user} mit {host}:{port} verbunden"),
    "glpi_db_ko": ("GLPI database connection failed: {err}", "Échec de connexion à la base GLPI : {err}",
                   "Fallo de conexión a la BD de GLPI: {err}", "Verbindung zur GLPI-Datenbank fehlgeschlagen: {err}"),
    "db_server_version": ("DB server version: {v}", "Version du serveur de base : {v}",
                          "Versión del servidor de BD: {v}", "Version des DB-Servers: {v}"),
    "glpi_dbname_ok": ("Database {db} accessible", "Base {db} accessible", "Base de datos {db} accesible",
                       "Datenbank {db} erreichbar"),
    "glpi_dbname_ko": ("Database {db} does not exist or is not accessible to this user",
                       "La base {db} n'existe pas ou n'est pas accessible à cet utilisateur",
                       "La base de datos {db} no existe o no es accesible para este usuario",
                       "Datenbank {db} existiert nicht oder ist für diesen Benutzer nicht zugänglich"),
    "check_error": ("Check could not be completed: {err}", "Vérification impossible : {err}",
                    "No se pudo completar la verificación: {err}", "Prüfung nicht möglich: {err}"),
    "hint_grant": ("On the GLPI DB server, as an administrator:", "Sur le serveur de base GLPI, en administrateur :",
                   "En el servidor de BD de GLPI, como administrador:", "Auf dem GLPI-DB-Server als Administrator:"),
    "hint_db_unreachable": ("The DB server {host}:{port} is down or does not accept remote connections",
                            "Le serveur {host}:{port} est arrêté ou n'accepte pas les connexions distantes",
                            "El servidor {host}:{port} está detenido o no acepta conexiones remotas",
                            "Der DB-Server {host}:{port} läuft nicht oder akzeptiert keine Remote-Verbindungen"),
    "hint_host_not_allowed": ("User {user} is not allowed to connect from the Medulla IP",
                              "L'utilisateur {user} n'est pas autorisé à se connecter depuis l'IP de Medulla",
                              "El usuario {user} no puede conectarse desde la IP de Medulla",
                              "Benutzer {user} darf sich nicht von der Medulla-IP verbinden"),
    "hint_access_denied": ("Wrong password for {user}, or user not defined for the Medulla IP",
                           "Mot de passe incorrect pour {user}, ou utilisateur non défini pour l'IP de Medulla",
                           "Contraseña incorrecta para {user}, o usuario no definido para la IP de Medulla",
                           "Falsches Passwort für {user} oder Benutzer für die Medulla-IP nicht angelegt"),

    # GLPI version / SQL file
    "not_glpi_db": ("glpi_configs table unreadable — is this really a GLPI database? ({err})",
                    "Table glpi_configs illisible — est-ce bien une base GLPI ? ({err})",
                    "Tabla glpi_configs no legible — ¿es realmente una BD de GLPI? ({err})",
                    "Tabelle glpi_configs nicht lesbar — ist das wirklich eine GLPI-Datenbank? ({err})"),
    "glpi_version_unknown": ("GLPI version not found in glpi_configs", "Version de GLPI introuvable dans glpi_configs",
                             "Versión de GLPI no encontrada en glpi_configs", "GLPI-Version in glpi_configs nicht gefunden"),
    "glpi_version_ok": ("GLPI version {v} detected", "Version de GLPI détectée : {v}",
                        "Versión de GLPI detectada: {v}", "GLPI-Version {v} erkannt"),
    "glpi_version_unsupported": ("GLPI {v} is not supported (GLPI 10 or 11 required)",
                                 "GLPI {v} n'est pas supporté (GLPI 10 ou 11 requis)",
                                 "GLPI {v} no está soportado (se requiere GLPI 10 u 11)",
                                 "GLPI {v} wird nicht unterstützt (GLPI 10 oder 11 erforderlich)"),
    "hint_supported_versions": ("Upgrade GLPI to version 10 or 11 first",
                                "Mettez d'abord GLPI à jour en version 10 ou 11",
                                "Actualice primero GLPI a la versión 10 u 11",
                                "Aktualisieren Sie GLPI zuerst auf Version 10 oder 11"),
    "glpi_dbversion_mismatch": ("GLPI code is {v} but the database schema is {dbv}",
                                "Le code GLPI est en {v} mais le schéma de la base est en {dbv}",
                                "El código de GLPI es {v} pero el esquema de la BD es {dbv}",
                                "GLPI-Code ist {v}, das Datenbankschema aber {dbv}"),
    "hint_glpi_update_db": ("Finish the GLPI update: php bin/console db:update",
                            "Terminez la mise à jour de GLPI : php bin/console db:update",
                            "Termine la actualización de GLPI: php bin/console db:update",
                            "GLPI-Update abschließen: php bin/console db:update"),
    "sql_notice_title": ("IMPORTANT — GLPI {major} detected", "IMPORTANT — GLPI {major} détecté",
                         "IMPORTANTE — GLPI {major} detectado", "WICHTIG — GLPI {major} erkannt"),
    "sql_notice_body": ("The file {file} must be applied to the GLPI database (Medulla views):",
                        "Le fichier {file} doit être appliqué sur la base GLPI (vues Medulla) :",
                        "El archivo {file} debe aplicarse a la BD de GLPI (vistas de Medulla):",
                        "Die Datei {file} muss auf die GLPI-Datenbank angewendet werden (Medulla-Views):"),
    "sql_notice_backup": ("Back up the GLPI database first (mysqldump), then:",
                          "Sauvegardez d'abord la base GLPI (mysqldump), puis :",
                          "Haga antes una copia de seguridad de la BD de GLPI (mysqldump) y luego:",
                          "Sichern Sie zuerst die GLPI-Datenbank (mysqldump), dann:"),
    "sql_notice_after": ("The required views are checked right after.",
                         "Les vues requises sont vérifiées juste après.",
                         "Las vistas requeridas se verifican justo después.",
                         "Die erforderlichen Views werden direkt danach geprüft."),

    # Schema
    "tables_missing": ("{n} missing table(s): {list}", "{n} table(s) manquante(s) : {list}",
                       "{n} tabla(s) faltante(s): {list}", "{n} fehlende Tabelle(n): {list}"),
    "tables_ok": ("All {n} required tables found", "Les {n} tables requises sont présentes",
                  "Las {n} tablas requeridas están presentes", "Alle {n} erforderlichen Tabellen vorhanden"),
    "hint_glpiinventory": ("Install and activate the GLPI Inventory plugin (glpiinventory) in GLPI",
                           "Installez et activez le plugin GLPI Inventory (glpiinventory) dans GLPI",
                           "Instale y active el plugin GLPI Inventory (glpiinventory) en GLPI",
                           "Installieren und aktivieren Sie das Plugin GLPI Inventory (glpiinventory) in GLPI"),
    "views_missing": ("{n} missing view(s): {list}", "{n} vue(s) manquante(s) : {list}",
                      "{n} vista(s) faltante(s): {list}", "{n} fehlende View(s): {list}"),
    "views_ok": ("All {n} required views found", "Les {n} vues requises sont présentes",
                 "Las {n} vistas requeridas están presentes", "Alle {n} erforderlichen Views vorhanden"),
    "views_broken": ("View(s) present but in error: {list}", "Vue(s) présente(s) mais en erreur : {list}",
                     "Vista(s) presente(s) pero con error: {list}", "View(s) vorhanden, aber fehlerhaft: {list}"),
    "views_query_ok": ("All views can be queried", "Toutes les vues sont interrogeables",
                       "Todas las vistas se pueden consultar", "Alle Views sind abfragbar"),
    "hint_apply_sql": ("Apply {url} to the GLPI database", "Appliquez {url} sur la base GLPI",
                       "Aplique {url} a la BD de GLPI", "Wenden Sie {url} auf die GLPI-Datenbank an"),
    "rechecking": ("Checking the views again…", "Nouvelle vérification des vues…",
                   "Verificando de nuevo las vistas…", "Views werden erneut geprüft…"),
    "sql_choice_title": ("Required views are missing. What do you want to do?",
                         "Des vues requises sont absentes. Que voulez-vous faire ?",
                         "Faltan vistas requeridas. ¿Qué desea hacer?",
                         "Erforderliche Views fehlen. Was möchten Sie tun?"),
    "sql_choice_auto": ("Download and apply {file} now (needs CREATE VIEW / DROP rights)",
                        "Télécharger et appliquer {file} maintenant (droits CREATE VIEW / DROP requis)",
                        "Descargar y aplicar {file} ahora (requiere permisos CREATE VIEW / DROP)",
                        "{file} jetzt herunterladen und anwenden (CREATE VIEW- / DROP-Rechte nötig)"),
    "sql_choice_manual": ("I have applied it manually — check again", "Je l'ai appliqué manuellement — revérifier",
                          "Lo he aplicado manualmente — verificar de nuevo",
                          "Ich habe sie manuell angewendet — erneut prüfen"),
    "sql_choice_skip": ("Continue without it", "Continuer sans", "Continuar sin él", "Ohne fortfahren"),
    "sql_confirm_auto": ("Apply {file} to database {db} on {host}?", "Appliquer {file} sur la base {db} de {host} ?",
                         "¿Aplicar {file} a la base de datos {db} en {host}?",
                         "{file} auf die Datenbank {db} auf {host} anwenden?"),
    "sql_download_ok": ("{file} downloaded", "{file} téléchargé", "{file} descargado", "{file} heruntergeladen"),
    "sql_download_ko": ("Download of {url} failed: {err}", "Échec du téléchargement de {url} : {err}",
                        "Fallo al descargar {url}: {err}", "Download von {url} fehlgeschlagen: {err}"),
    "sql_apply_ok": ("{file} applied to the GLPI database", "{file} appliqué sur la base GLPI",
                     "{file} aplicado a la BD de GLPI", "{file} auf die GLPI-Datenbank angewendet"),
    "sql_apply_ko": ("Applying {file} failed: {err}", "Échec de l'application de {file} : {err}",
                     "Fallo al aplicar {file}: {err}", "Anwenden von {file} fehlgeschlagen: {err}"),
    "sql_no_mysql_client": ("mysql client not installed: the SQL file must be applied manually",
                            "Client mysql absent : le fichier SQL doit être appliqué manuellement",
                            "Cliente mysql no instalado: el archivo SQL debe aplicarse manualmente",
                            "mysql-Client nicht installiert: die SQL-Datei muss manuell angewendet werden"),

    # Privileges
    "grants_found": ("Privileges on {db}: {list}", "Droits sur {db} : {list}", "Privilegios sobre {db}: {list}",
                     "Rechte auf {db}: {list}"),
    "grants_missing": ("Privileges possibly missing: {list}", "Droits potentiellement manquants : {list}",
                       "Privilegios posiblemente faltantes: {list}", "Möglicherweise fehlende Rechte: {list}"),
    "grants_ok": ("Privileges sufficient for the selected mode", "Droits suffisants pour le mode choisi",
                  "Privilegios suficientes para el modo elegido", "Rechte für den gewählten Modus ausreichend"),
    "grants_no_create_view": ("This user cannot create views: the SQL file must be applied by a GLPI DB administrator",
                              "Cet utilisateur ne peut pas créer de vues : le fichier SQL devra être appliqué par un administrateur de la base GLPI",
                              "Este usuario no puede crear vistas: el archivo SQL deberá aplicarlo un administrador de la BD de GLPI",
                              "Dieser Benutzer kann keine Views anlegen: die SQL-Datei muss ein GLPI-DB-Administrator anwenden"),

    # Plugins
    "plugin_state": ("Plugin {name} {v}: {state}",),
    "plugin_on": ("activated", "activé", "activado", "aktiviert"),
    "plugin_off": ("not activated (state {s})", "non activé (état {s})", "no activado (estado {s})",
                   "nicht aktiviert (Status {s})"),
    "fusion_incompatible": ("FusionInventory is not compatible with GLPI 10/11",
                            "FusionInventory n'est pas compatible avec GLPI 10/11",
                            "FusionInventory no es compatible con GLPI 10/11",
                            "FusionInventory ist nicht mit GLPI 10/11 kompatibel"),
    "hint_use_glpiinventory": ("Use the glpiinventory plugin and the glpiagent agent",
                               "Utilisez le plugin glpiinventory et l'agent glpiagent",
                               "Use el plugin glpiinventory y el agente glpiagent",
                               "Verwenden Sie das Plugin glpiinventory und den Agenten glpiagent"),
    "plugin_missing": ("Plugin {name} is not installed in GLPI", "Le plugin {name} n'est pas installé dans GLPI",
                       "El plugin {name} no está instalado en GLPI", "Plugin {name} ist in GLPI nicht installiert"),
    "plugin_inactive": ("Plugin {name} is installed but not activated", "Le plugin {name} est installé mais pas activé",
                        "El plugin {name} está instalado pero no activado",
                        "Plugin {name} ist installiert, aber nicht aktiviert"),
    "hint_activate_plugin": ("GLPI: Setup > Plugins", "GLPI : Configuration > Plugins", "GLPI: Configuración > Plugins",
                             "GLPI: Einrichten > Plugins"),
    "plugin_ok": ("Plugin {name} {v} activated", "Plugin {name} {v} activé", "Plugin {name} {v} activado",
                  "Plugin {name} {v} aktiviert"),
    "plugin_none": ("No inventory plugin installed", "Aucun plugin d'inventaire installé",
                    "Ningún plugin de inventario instalado", "Kein Inventar-Plugin installiert"),

    # GLPI settings
    "url_base_mismatch": ("URL declared in GLPI ({glpi}) differs from the configured one ({medulla})",
                          "L'URL déclarée dans GLPI ({glpi}) diffère de celle configurée ({medulla})",
                          "La URL declarada en GLPI ({glpi}) difiere de la configurada ({medulla})",
                          "Die in GLPI hinterlegte URL ({glpi}) weicht von der konfigurierten ab ({medulla})"),
    "url_base_ok": ("GLPI URL consistent: {url}", "URL GLPI cohérente : {url}", "URL de GLPI coherente: {url}",
                    "GLPI-URL stimmig: {url}"),
    "api_enabled_ok": ("REST API enabled", "API REST activée", "API REST activada", "REST-API aktiviert"),
    "api_enabled_ko": ("REST API disabled in GLPI", "API REST désactivée dans GLPI", "API REST desactivada en GLPI",
                       "REST-API in GLPI deaktiviert"),
    "api_login_cred_ok": ("API login with credentials enabled", "Connexion API par identifiants activée",
                          "Inicio de sesión API con credenciales activado", "API-Anmeldung mit Zugangsdaten aktiviert"),
    "api_login_cred_ko": ("API login with credentials disabled", "Connexion API par identifiants désactivée",
                          "Inicio de sesión API con credenciales desactivado", "API-Anmeldung mit Zugangsdaten deaktiviert"),
    "api_login_token_ok": ("API login with external token enabled", "Connexion API par jeton externe activée",
                           "Inicio de sesión API con token externo activado", "API-Anmeldung mit externem Token aktiviert"),
    "api_login_token_ko": ("API login with external token disabled", "Connexion API par jeton externe désactivée",
                           "Inicio de sesión API con token externo desactivado",
                           "API-Anmeldung mit externem Token deaktiviert"),
    "hint_glpi_api_setup": ("GLPI: Setup > General > API", "GLPI : Configuration > Générale > API",
                            "GLPI: Configuración > General > API", "GLPI: Einrichten > Allgemein > API"),
    "inventory_enabled_ok": ("GLPI inventory enabled", "Inventaire GLPI activé", "Inventario de GLPI activado",
                             "GLPI-Inventar aktiviert"),
    "inventory_enabled_unknown": ("Cannot tell whether GLPI inventory is enabled",
                                  "Impossible de savoir si l'inventaire GLPI est activé",
                                  "No se puede saber si el inventario de GLPI está activado",
                                  "Nicht feststellbar, ob das GLPI-Inventar aktiviert ist"),
    "inventory_enabled_ko": ("GLPI inventory is disabled: forwarded inventories will be rejected",
                             "L'inventaire GLPI est désactivé : les inventaires remontés seront rejetés",
                             "El inventario de GLPI está desactivado: los inventarios reenviados serán rechazados",
                             "GLPI-Inventar ist deaktiviert: weitergeleitete Inventare werden abgelehnt"),
    "hint_enable_inventory": ("GLPI: Administration > Inventory > Enable inventory",
                              "GLPI : Administration > Inventaire > Activer l'inventaire",
                              "GLPI: Administración > Inventario > Activar inventario",
                              "GLPI: Verwaltung > Inventar > Inventar aktivieren"),

    # API client / user
    "mmc_client_missing": ("No API client named {name} in glpi_apiclients",
                           "Aucun client API nommé {name} dans glpi_apiclients",
                           "Ningún cliente API llamado {name} en glpi_apiclients",
                           "Kein API-Client namens {name} in glpi_apiclients"),
    "hint_create_mmc": ("GLPI: Setup > General > API > Add API client, name: {name}",
                        "GLPI : Configuration > Générale > API > Ajouter un client de l'API, nom : {name}",
                        "GLPI: Configuración > General > API > Añadir cliente API, nombre: {name}",
                        "GLPI: Einrichten > Allgemein > API > API-Client hinzufügen, Name: {name}"),
    "mmc_client_multiple": ("{n} API clients are named {name}: the first one is checked",
                            "{n} clients API s'appellent {name} : le premier est vérifié",
                            "{n} clientes API se llaman {name}: se verifica el primero",
                            "{n} API-Clients heißen {name}: der erste wird geprüft"),
    "mmc_client_ok": ("API client {name} found and active", "Client API {name} trouvé et actif",
                      "Cliente API {name} encontrado y activo", "API-Client {name} gefunden und aktiv"),
    "tok_app": ("App-Token of API client {name}", "App-Token du client API {name}",
                "App-Token del cliente API {name}", "App-Token des API-Clients {name}"),
    "tok_user": ("API token of user {user}", "Jeton API de l'utilisateur {user}",
                 "Token API del usuario {user}", "API-Token des Benutzers {user}"),
    "token_plain": ("{what}: stored in clear in GLPI", "{what} : stocké en clair dans GLPI",
                    "{what}: almacenado sin cifrar en GLPI", "{what}: im Klartext in GLPI gespeichert"),
    "token_matches_saas": ("{what}: identical to the value configured for Medulla (saas_application)",
                           "{what} : identique à la valeur configurée pour Medulla (saas_application)",
                           "{what}: idéntico al valor configurado para Medulla (saas_application)",
                           "{what}: identisch mit dem für Medulla konfigurierten Wert (saas_application)"),
    "token_differs_saas": ("{what}: differs from the value configured for Medulla (saas_application)",
                           "{what} : différent de la valeur configurée pour Medulla (saas_application)",
                           "{what}: distinto del valor configurado para Medulla (saas_application)",
                           "{what}: weicht vom für Medulla konfigurierten Wert ab (saas_application)"),
    "token_not_plain": ("{what}: {kind} in GLPI — it cannot be copied into saas_application, its clear value must be entered",
                        "{what} : {kind} dans GLPI — il ne peut pas être reporté dans saas_application, sa valeur en clair doit être saisie",
                        "{what}: {kind} en GLPI — no puede copiarse en saas_application, debe introducirse su valor sin cifrar",
                        "{what}: {kind} in GLPI — kann nicht in saas_application übernommen werden, der Klartextwert muss eingegeben werden"),
    "token_empty": ("{what}: no token in GLPI", "{what} : aucun jeton dans GLPI",
                    "{what}: ningún token en GLPI", "{what}: kein Token in GLPI"),
    "token_saas_empty_copyable": ("{what}: missing from saas_application — fix mode will copy it from GLPI",
                                  "{what} : absent de saas_application — le mode correction le reportera depuis GLPI",
                                  "{what}: ausente de saas_application — el modo corrección lo copiará desde GLPI",
                                  "{what}: fehlt in saas_application — der Korrekturmodus übernimmt es aus GLPI"),
    "token_saas_missing": ("{what}: missing from saas_application, and it cannot be taken from GLPI",
                           "{what} : absent de saas_application, et il ne peut pas être repris depuis GLPI",
                           "{what}: ausente de saas_application, y no puede tomarse de GLPI",
                           "{what}: fehlt in saas_application und kann nicht aus GLPI übernommen werden"),
    "token_saas_not_clear": ("{what}: the value in saas_application is not in clear (it must be)",
                             "{what} : la valeur dans saas_application n'est pas en clair (elle doit l'être)",
                             "{what}: el valor en saas_application no está en claro (debe estarlo)",
                             "{what}: der Wert in saas_application ist nicht im Klartext (muss er aber sein)"),
    "token_matches_saas_decrypted": ("{what}: saas_application matches the GLPI token once decrypted",
                                     "{what} : saas_application correspond au jeton GLPI une fois déchiffré",
                                     "{what}: saas_application coincide con el token de GLPI una vez descifrado",
                                     "{what}: saas_application entspricht dem entschlüsselten GLPI-Token"),
    "token_differs_saas_decrypted": ("{what}: saas_application differs from the GLPI token once decrypted",
                                     "{what} : saas_application diffère du jeton GLPI une fois déchiffré",
                                     "{what}: saas_application difiere del token de GLPI una vez descifrado",
                                     "{what}: saas_application weicht vom entschlüsselten GLPI-Token ab"),
    "token_saas_unverifiable": ("{what}: present in clear in saas_application, cannot be compared with GLPI (the API test is authoritative)",
                                "{what} : présent en clair dans saas_application, comparaison impossible avec GLPI (le test API fait foi)",
                                "{what}: presente en claro en saas_application, no se puede comparar con GLPI (la prueba API es la referencia)",
                                "{what}: im Klartext in saas_application vorhanden, Vergleich mit GLPI nicht möglich (der API-Test ist maßgeblich)"),
    "token_kind_hashed": ("hashed", "haché", "con hash", "gehasht"),
    "token_kind_encrypted": ("encrypted", "chiffré", "cifrado", "verschlüsselt"),
    "token_kind_unknown": ("in an unknown format", "dans un format inconnu", "en un formato desconocido",
                           "in einem unbekannten Format"),
    "hint_token_enter_clear": ("Regenerate the token in GLPI, copy the displayed value and enter it in fix mode",
                               "Régénérez le jeton dans GLPI, copiez la valeur affichée et saisissez-la en mode correction",
                               "Regenere el token en GLPI, copie el valor mostrado e introdúzcalo en modo corrección",
                               "Token in GLPI neu erzeugen, angezeigten Wert kopieren und im Korrekturmodus eingeben"),
    "hint_regen_user_token": ("GLPI: Administration > Users > {user} > Remote access keys > API token > Regenerate",
                              "GLPI : Administration > Utilisateurs > {user} > Clés d'accès distant > Jeton d'API > Régénérer",
                              "GLPI: Administración > Usuarios > {user} > Claves de acceso remoto > Token de API > Regenerar",
                              "GLPI: Verwaltung > Benutzer > {user} > Fernzugriffsschlüssel > API-Token > Neu erzeugen"),
    "token_autofill": ("{what}: read in clear from GLPI, it will be written to saas_application",
                       "{what} : lu en clair dans GLPI, il sera reporté dans saas_application",
                       "{what}: leído sin cifrar en GLPI, se escribirá en saas_application",
                       "{what}: im Klartext aus GLPI gelesen, wird in saas_application eingetragen"),
    "token_must_enter": ("{what}: {kind} in GLPI, enter its clear value",
                         "{what} : {kind} dans GLPI, saisissez sa valeur en clair",
                         "{what}: {kind} en GLPI, introduzca su valor sin cifrar",
                         "{what}: {kind} in GLPI, Klartextwert eingeben"),
    "apiclient_inactive": ("API client '{name}' is not active", "Le client API « {name} » n'est pas actif",
                           "El cliente API «{name}» no está activo", "API-Client „{name}“ ist nicht aktiv"),
    "apiclient_ip_ok": ("Medulla IP {ip} within the allowed range {range}",
                        "IP de Medulla {ip} dans la plage autorisée {range}",
                        "IP de Medulla {ip} dentro del rango permitido {range}",
                        "Medulla-IP {ip} im erlaubten Bereich {range}"),
    "apiclient_ip_ko": ("Medulla IP {ip} outside the API client's allowed range {range}",
                        "IP de Medulla {ip} hors de la plage autorisée du client API {range}",
                        "IP de Medulla {ip} fuera del rango permitido del cliente API {range}",
                        "Medulla-IP {ip} außerhalb des erlaubten Bereichs des API-Clients {range}"),
    "hint_apiclient_ip": ("Widen the IPv4 range of the API client (unless Medulla is behind NAT)",
                          "Élargissez la plage IPv4 du client API (sauf si Medulla est derrière un NAT)",
                          "Amplíe el rango IPv4 del cliente API (salvo si Medulla está detrás de un NAT)",
                          "IPv4-Bereich des API-Clients erweitern (außer Medulla steht hinter NAT)"),
    "apiclient_no_iprange": ("API client has no IP restriction", "Le client API n'a pas de restriction IP",
                             "El cliente API no tiene restricción de IP", "API-Client hat keine IP-Beschränkung"),
    "apiuser_missing": ("API user '{user}' does not exist in GLPI", "L'utilisateur API « {user} » n'existe pas dans GLPI",
                        "El usuario API «{user}» no existe en GLPI", "API-Benutzer „{user}“ existiert nicht in GLPI"),
    "apiuser_deleted": ("API user '{user}' is in the GLPI trash", "L'utilisateur API « {user} » est dans la corbeille GLPI",
                        "El usuario API «{user}» está en la papelera de GLPI", "API-Benutzer „{user}“ liegt im GLPI-Papierkorb"),
    "apiuser_inactive": ("API user '{user}' is disabled", "L'utilisateur API « {user} » est désactivé",
                         "El usuario API «{user}» está desactivado", "API-Benutzer „{user}“ ist deaktiviert"),
    "apiuser_ok": ("API user '{user}' exists and is active", "L'utilisateur API « {user} » existe et est actif",
                   "El usuario API «{user}» existe y está activo", "API-Benutzer „{user}“ existiert und ist aktiv"),

    # Crypt key
    "cryptkey_missing": ("GLPI crypt key not set", "Clé de chiffrement GLPI non renseignée",
                         "Clave de cifrado de GLPI no definida", "GLPI-Schlüssel nicht gesetzt"),
    "cryptkey_not_b64": ("Crypt key is not valid base64", "La clé n'est pas un base64 valide",
                         "La clave no es base64 válido", "Schlüssel ist kein gültiges Base64"),
    "cryptkey_len": ("Decoded crypt key is {n} bytes (32 expected)", "La clé décodée fait {n} octets (32 attendus)",
                     "La clave decodificada tiene {n} bytes (se esperan 32)",
                     "Dekodierter Schlüssel hat {n} Bytes (32 erwartet)"),
    "cryptkey_format_ok": ("Crypt key format valid (32 bytes)", "Format de clé valide (32 octets)",
                           "Formato de clave válido (32 bytes)", "Schlüsselformat gültig (32 Bytes)"),
    "cryptkey_no_nacl": ("Key not validated against GLPI data (python3-nacl missing)",
                         "Clé non validée sur les données GLPI (python3-nacl absent)",
                         "Clave no validada con los datos de GLPI (falta python3-nacl)",
                         "Schlüssel nicht anhand der GLPI-Daten geprüft (python3-nacl fehlt)"),
    "cryptkey_no_sample": ("No encrypted value in GLPI to validate the key against",
                           "Aucune valeur chiffrée dans GLPI pour valider la clé",
                           "Ningún valor cifrado en GLPI para validar la clave",
                           "Kein verschlüsselter Wert in GLPI zur Prüfung des Schlüssels"),
    "cryptkey_match": ("Crypt key successfully decrypts GLPI data", "La clé déchiffre bien les données GLPI",
                       "La clave descifra correctamente los datos de GLPI",
                       "Schlüssel entschlüsselt GLPI-Daten erfolgreich"),
    "cryptkey_mismatch": ("Crypt key does not match this GLPI instance",
                          "La clé ne correspond pas à cette instance GLPI",
                          "La clave no corresponde a esta instancia de GLPI",
                          "Schlüssel passt nicht zu dieser GLPI-Instanz"),

    # Web / API
    "http_cleartext": ("{url} uses plain HTTP: credentials travel in clear text",
                       "{url} est en HTTP : les identifiants circulent en clair",
                       "{url} usa HTTP: las credenciales viajan sin cifrar",
                       "{url} nutzt HTTP: Zugangsdaten werden unverschlüsselt übertragen"),
    "ssl_ko": ("TLS certificate rejected for {url}: {err}", "Certificat TLS refusé pour {url} : {err}",
               "Certificado TLS rechazado para {url}: {err}", "TLS-Zertifikat für {url} abgelehnt: {err}"),
    "hint_ssl_ca": ("Add the CA to /usr/local/share/ca-certificates/ then run update-ca-certificates",
                    "Ajoutez l'AC dans /usr/local/share/ca-certificates/ puis lancez update-ca-certificates",
                    "Añada la CA en /usr/local/share/ca-certificates/ y ejecute update-ca-certificates",
                    "CA in /usr/local/share/ca-certificates/ ablegen und update-ca-certificates ausführen"),
    "hint_insecure": ("The remaining HTTP tests run without verification (--insecure to ignore TLS)",
                      "Les tests HTTP suivants sont faits sans vérification (--insecure pour ignorer TLS)",
                      "Las siguientes pruebas HTTP se hacen sin verificación (--insecure para ignorar TLS)",
                      "Die weiteren HTTP-Tests laufen ohne Prüfung (--insecure, um TLS zu ignorieren)"),
    "url_unreachable": ("{url} unreachable: {err}", "{url} injoignable : {err}", "{url} inaccesible: {err}",
                        "{url} nicht erreichbar: {err}"),
    "hint_firewall_web": ("Check DNS, proxy and firewalls between Medulla and GLPI",
                          "Vérifiez DNS, proxy et pare-feux entre Medulla et GLPI",
                          "Revise DNS, proxy y cortafuegos entre Medulla y GLPI",
                          "DNS, Proxy und Firewalls zwischen Medulla und GLPI prüfen"),
    "url_reachable": ("{url} reachable (HTTP {code})", "{url} joignable (HTTP {code})",
                      "{url} accesible (HTTP {code})", "{url} erreichbar (HTTP {code})"),
    "url_http_code": ("{url} answered HTTP {code}", "{url} a répondu HTTP {code}", "{url} respondió HTTP {code}",
                      "{url} antwortete mit HTTP {code}"),
    "api_url_v10": ("For GLPI 10 the API URL usually ends with /apirest.php ({url})",
                    "Pour GLPI 10, l'URL de l'API se termine normalement par /apirest.php ({url})",
                    "Para GLPI 10, la URL de la API suele terminar en /apirest.php ({url})",
                    "Bei GLPI 10 endet die API-URL normalerweise auf /apirest.php ({url})"),
    "api_url_v11": ("For GLPI 11 the API URL usually ends with /api.php/v1 ({url})",
                    "Pour GLPI 11, l'URL de l'API se termine normalement par /api.php/v1 ({url})",
                    "Para GLPI 11, la URL de la API suele terminar en /api.php/v1 ({url})",
                    "Bei GLPI 11 endet die API-URL normalerweise auf /api.php/v1 ({url})"),
    "hint_api_url": ("Suggested: {url}", "Suggestion : {url}", "Sugerencia: {url}", "Vorschlag: {url}"),
    "api_skip_readonly": ("Read-only mode: API authentication not tested",
                          "Mode lecture seule : authentification API non testée",
                          "Modo solo lectura: autenticación API no probada",
                          "Nur-Lese-Modus: API-Anmeldung nicht getestet"),
    "api_cred_ok": ("API authentication with login/password OK",
                    "Authentification API par identifiant/mot de passe OK",
                    "Autenticación API con usuario/contraseña OK", "API-Anmeldung mit Benutzer/Passwort OK"),
    "api_cred_ko": ("API authentication with login/password failed (HTTP {code}): {err}",
                    "Échec de l'authentification API par identifiant/mot de passe (HTTP {code}) : {err}",
                    "Fallo de autenticación API con usuario/contraseña (HTTP {code}): {err}",
                    "API-Anmeldung mit Benutzer/Passwort fehlgeschlagen (HTTP {code}): {err}"),
    "api_token_ok": ("API authentication with user token OK", "Authentification API par jeton utilisateur OK",
                     "Autenticación API con token de usuario OK", "API-Anmeldung mit Benutzertoken OK"),
    "api_token_ko": ("API authentication with user token failed (HTTP {code}): {err}",
                     "Échec de l'authentification API par jeton utilisateur (HTTP {code}) : {err}",
                     "Fallo de autenticación API con token de usuario (HTTP {code}): {err}",
                     "API-Anmeldung mit Benutzertoken fehlgeschlagen (HTTP {code}): {err}"),
    "hint_curl": ("To reproduce from the Medulla server:", "Pour reproduire depuis le serveur Medulla :",
                  "Para reproducirlo desde el servidor Medulla:", "Zum Nachstellen auf dem Medulla-Server:"),
    "api_profile": ("API session profile: {name} (interface {iface})",
                    "Profil de la session API : {name} (interface {iface})",
                    "Perfil de la sesión API: {name} (interfaz {iface})",
                    "Profil der API-Sitzung: {name} (Oberfläche {iface})"),
    "api_profile_helpdesk": ("The token user's default profile uses the simplified (helpdesk) interface",
                             "Le profil par défaut de l'utilisateur du jeton utilise l'interface simplifiée (helpdesk)",
                             "El perfil por defecto del usuario del token usa la interfaz simplificada (helpdesk)",
                             "Das Standardprofil des Token-Benutzers nutzt die vereinfachte Oberfläche (Helpdesk)"),
    "hint_profile": ("Give this user a central profile (e.g. Super-Admin) as default",
                     "Attribuez par défaut à cet utilisateur un profil standard (ex. Super-Admin)",
                     "Asigne por defecto a este usuario un perfil central (p. ej. Super-Admin)",
                     "Diesem Benutzer standardmäßig ein zentrales Profil (z. B. Super-Admin) zuweisen"),
    "forward_url_hint": ("Forward URL is usually {url}", "L'URL de remontée est habituellement {url}",
                         "La URL de reenvío suele ser {url}", "Die Weiterleitungs-URL lautet üblicherweise {url}"),

    # Medulla configuration
    "file_ok": ("{file} present", "{file} présent", "{file} presente", "{file} vorhanden"),
    "file_world_readable": ("{file} is world-readable ({mode}) and contains passwords",
                            "{file} est lisible par tous ({mode}) et contient des mots de passe",
                            "{file} es legible por todos ({mode}) y contiene contraseñas",
                            "{file} ist für alle lesbar ({mode}) und enthält Passwörter"),
    "hint_chmod": ("chmod 640 {file}",),
    "glpi_plugin_enabled": ("GLPI plugin enabled in Medulla (disable = 0)",
                            "Plugin GLPI activé dans Medulla (disable = 0)",
                            "Plugin GLPI activado en Medulla (disable = 0)",
                            "GLPI-Plugin in Medulla aktiviert (disable = 0)"),
    "glpi_plugin_disabled": ("GLPI plugin disabled in Medulla", "Plugin GLPI désactivé dans Medulla",
                             "Plugin GLPI desactivado en Medulla", "GLPI-Plugin in Medulla deaktiviert"),
    "hint_fix_mode": ("Run this script in fix mode", "Lancez ce script en mode correction",
                      "Ejecute este script en modo corrección", "Dieses Skript im Korrekturmodus ausführen"),
    "conf_mismatch": ("{file}: values differ from glpi.ini.local ({keys})",
                      "{file} : valeurs différentes de glpi.ini.local ({keys})",
                      "{file}: valores distintos de glpi.ini.local ({keys})",
                      "{file}: Werte weichen von glpi.ini.local ab ({keys})"),
    "conf_consistent": ("{file} consistent", "{file} cohérent", "{file} coherente", "{file} stimmig"),
    "client_agent_ok": ("Client inventory agent: {agent}", "Agent d'inventaire client : {agent}",
                        "Agente de inventario cliente: {agent}", "Client-Inventar-Agent: {agent}"),
    "client_agent_mismatch": ("{file}: inventory agent does not match ({agent} expected)",
                              "{file} : l'agent d'inventaire ne correspond pas ({agent} attendu)",
                              "{file}: el agente de inventario no coincide (se espera {agent})",
                              "{file}: Inventar-Agent passt nicht ({agent} erwartet)"),
    "regagent_mismatch": ("{file}: check_uuidinventory inconsistent with the read-only mode",
                          "{file} : check_uuidinventory incohérent avec le mode lecture seule",
                          "{file}: check_uuidinventory incoherente con el modo solo lectura",
                          "{file}: check_uuidinventory passt nicht zum Nur-Lese-Modus"),
    "saas_empty": ("Empty API settings in admin.saas_application: {list}",
                   "Paramètres API vides dans admin.saas_application : {list}",
                   "Parámetros API vacíos en admin.saas_application: {list}",
                   "Leere API-Einstellungen in admin.saas_application: {list}"),
    "saas_ok": ("API settings present in admin.saas_application",
                "Paramètres API présents dans admin.saas_application",
                "Parámetros API presentes en admin.saas_application",
                "API-Einstellungen in admin.saas_application vorhanden"),
    "saas_url_mismatch": ("API URL differs between admin.saas_application ({saas}) and glpi.ini.local ({ini})",
                          "L'URL API diffère entre admin.saas_application ({saas}) et glpi.ini.local ({ini})",
                          "La URL de la API difiere entre admin.saas_application ({saas}) y glpi.ini.local ({ini})",
                          "API-URL unterscheidet sich zwischen admin.saas_application ({saas}) und glpi.ini.local ({ini})"),

    # Federated
    "fedserver_missing": ("Federated server itsm_federated does not exist",
                          "Le serveur fédéré itsm_federated n'existe pas",
                          "El servidor federado itsm_federated no existe",
                          "Föderierter Server itsm_federated existiert nicht"),
    "fedserver_mismatch": ("Federated server itsm_federated points elsewhere ({list})",
                           "Le serveur fédéré itsm_federated pointe ailleurs ({list})",
                           "El servidor federado itsm_federated apunta a otro destino ({list})",
                           "Föderierter Server itsm_federated zeigt woandershin ({list})"),
    "fedserver_ok": ("Federated server itsm_federated (on the Medulla DB) → {host}:{port}/{db}",
                     "Serveur fédéré itsm_federated (sur la base Medulla) → {host}:{port}/{db}",
                     "Servidor federado itsm_federated (en la BD de Medulla) → {host}:{port}/{db}",
                     "Föderierter Server itsm_federated (in der Medulla-DB) → {host}:{port}/{db}"),
    "fedserver_unreadable": ("Cannot read mysql.servers: {err}", "Lecture de mysql.servers impossible : {err}",
                             "No se puede leer mysql.servers: {err}", "mysql.servers nicht lesbar: {err}"),
    "fedtables_ko": ("{n} federated table(s) in error", "{n} table(s) fédérée(s) en erreur",
                     "{n} tabla(s) federada(s) con error", "{n} föderierte Tabelle(n) fehlerhaft"),
    "fedtables_ok": ("All {n} federated tables can be queried", "Les {n} tables fédérées sont interrogeables",
                     "Las {n} tablas federadas se pueden consultar", "Alle {n} föderierten Tabellen sind abfragbar"),
    "glpi_machines_count": ("Computers visible in GLPI through federation: {n}",
                            "Ordinateurs visibles dans GLPI via la fédération : {n}",
                            "Equipos visibles en GLPI mediante federación: {n}",
                            "Über die Föderation sichtbare GLPI-Computer: {n}"),
    "medulla_machines_count": ("Machines registered in Medulla: {n}", "Machines enregistrées dans Medulla : {n}",
                               "Equipos registrados en Medulla: {n}", "In Medulla registrierte Maschinen: {n}"),

    # Services
    "service_ok": ("{svc} active", "{svc} actif", "{svc} activo", "{svc} aktiv"),
    "service_ko": ("{svc} not active ({state})", "{svc} inactif ({state})", "{svc} no activo ({state})",
                   "{svc} nicht aktiv ({state})"),

    # Fix mode
    "preflight_title": ("Pre-flight checks of the entered parameters", "Vérifications préalables des paramètres saisis",
                        "Verificaciones previas de los parámetros introducidos", "Vorabprüfung der eingegebenen Parameter"),
    "preflight_summary": ("Pre-flight summary", "Bilan des vérifications préalables",
                          "Resumen de las verificaciones previas", "Ergebnis der Vorabprüfung"),
    "abort_preflight_failed": ("Pre-flight checks failed: nothing was changed (--force to apply anyway).",
                               "Les vérifications préalables ont échoué : rien n'a été modifié (--force pour appliquer quand même).",
                               "Las verificaciones previas fallaron: no se ha modificado nada (--force para aplicar de todos modos).",
                               "Vorabprüfung fehlgeschlagen: nichts wurde geändert (--force, um trotzdem anzuwenden)."),
    "preflight_failed_choice": ("Some pre-flight checks failed. What next?",
                                "Certaines vérifications préalables ont échoué. Que faire ?",
                                "Algunas verificaciones previas fallaron. ¿Qué hacer?",
                                "Einige Vorabprüfungen sind fehlgeschlagen. Wie weiter?"),
    "choice_edit": ("Edit the parameters", "Modifier les paramètres", "Modificar los parámetros",
                    "Parameter bearbeiten"),
    "choice_force": ("Apply anyway", "Appliquer quand même", "Aplicar de todos modos", "Trotzdem anwenden"),
    "choice_abort": ("Abort (nothing is changed)", "Abandonner (rien n'est modifié)",
                     "Cancelar (no se modifica nada)", "Abbrechen (nichts wird geändert)"),
    "force_continue": ("--force: applying despite failed pre-flight checks",
                       "--force : application malgré les échecs",
                       "--force: se aplica a pesar de los fallos", "--force: Anwendung trotz Fehlern"),
    "plan_title": ("The following changes will be made:", "Les modifications suivantes vont être effectuées :",
                   "Se realizarán los siguientes cambios:", "Folgende Änderungen werden vorgenommen:"),
    "plan_backup": ("backup of every modified file into a backup/ folder next to it (<file>.YYYYmmdd-HHMMSS)",
                    "sauvegarde de chaque fichier modifié dans un dossier backup/ au même endroit (<fichier>.AAAAMMJJ-HHMMSS)",
                    "copia de cada archivo modificado en una carpeta backup/ en el mismo lugar (<archivo>.AAAAMMDD-HHMMSS)",
                    "Sicherung jeder geänderten Datei in einen Ordner backup/ am selben Ort (<Datei>.JJJJMMTT-HHMMSS)"),
    "plan_update_file": ("update {file}", "mise à jour de {file}", "actualización de {file}",
                         "Aktualisierung von {file}"),
    "plan_federated": ("(re)define the federated server itsm_federated on the local Medulla MariaDB, create only the missing local_glpi_* tables (existing ones are kept)",
                       "(re)définition du serveur fédéré itsm_federated sur le MariaDB local de Medulla, création des seules tables local_glpi_* manquantes (les existantes sont conservées)",
                       "(re)definición del servidor federado itsm_federated en el MariaDB local de Medulla, creación solo de las tablas local_glpi_* que faltan (las existentes se conservan)",
                       "(Neu-)Definition des föderierten Servers itsm_federated im lokalen MariaDB von Medulla, Anlage nur fehlender local_glpi_*-Tabellen (vorhandene bleiben erhalten)"),
    "plan_saas": ("update the API settings in admin.saas_application",
                  "mise à jour des paramètres API dans admin.saas_application",
                  "actualización de los parámetros API en admin.saas_application",
                  "Aktualisierung der API-Einstellungen in admin.saas_application"),
    "plan_forward_off": ("disable inventory forwarding in {file}",
                         "désactivation de la remontée d'inventaire dans {file}",
                         "desactivación del reenvío de inventario en {file}",
                         "Deaktivierung der Inventarweiterleitung in {file}"),
    "plan_restart": ("restart: {list}", "redémarrage : {list}", "reinicio: {list}", "Neustart: {list}"),
    "plan_reconf": ("ask every Medulla agent to reconfigure (need_reconf=1)",
                    "demande de reconfiguration de tous les agents Medulla (need_reconf=1)",
                    "solicitud de reconfiguración de todos los agentes Medulla (need_reconf=1)",
                    "Neukonfiguration aller Medulla-Agenten anfordern (need_reconf=1)"),
    "plan_regen": ("regenerate the Medulla agent installer without the inventory agent",
                   "régénération de l'installeur de l'agent Medulla sans agent d'inventaire",
                   "regeneración del instalador del agente Medulla sin agente de inventario",
                   "Neuerstellung des Medulla-Agent-Installers ohne Inventar-Agent"),
    "confirm_apply": ("Apply these changes?", "Appliquer ces modifications ?", "¿Aplicar estos cambios?",
                      "Diese Änderungen anwenden?"),
    "backup_ok": ("Backup: {dst}", "Sauvegarde : {dst}", "Copia de seguridad: {dst}", "Sicherung: {dst}"),
    "file_written": ("{file} updated", "{file} mis à jour", "{file} actualizado", "{file} aktualisiert"),
    "write_ko": ("Cannot update {file}: {err}", "Impossible de mettre à jour {file} : {err}",
                 "No se puede actualizar {file}: {err}", "{file} kann nicht aktualisiert werden: {err}"),
    "fed_priv_ok": ("Account {user} may create the federated server", "Le compte {user} peut créer le serveur fédéré",
                    "La cuenta {user} puede crear el servidor federado", "Konto {user} darf den föderierten Server anlegen"),
    "fed_priv_root": ("Account {user} lacks FEDERATED ADMIN: root (local socket) will create the federated server",
                      "Le compte {user} n'a pas FEDERATED ADMIN : root (socket local) créera le serveur fédéré",
                      "La cuenta {user} no tiene FEDERATED ADMIN: root (socket local) creará el servidor federado",
                      "Konto {user} fehlt FEDERATED ADMIN: root (lokaler Socket) legt den föderierten Server an"),
    "fed_priv_ko": ("Neither {user} nor root (local socket) may create the federated server (SUPER / FEDERATED ADMIN needed)",
                    "Ni {user} ni root (socket local) ne peuvent créer le serveur fédéré (SUPER / FEDERATED ADMIN requis)",
                    "Ni {user} ni root (socket local) pueden crear el servidor federado (se requiere SUPER / FEDERATED ADMIN)",
                    "Weder {user} noch root (lokaler Socket) dürfen den föderierten Server anlegen (SUPER / FEDERATED ADMIN nötig)"),
    "hint_fed_priv": ("Run the script as root, or grant the privilege on the Medulla MariaDB:",
                      "Lancez le script en root, ou donnez le droit sur le MariaDB de Medulla :",
                      "Ejecute el script como root, o conceda el privilegio en el MariaDB de Medulla:",
                      "Skript als root ausführen oder das Recht im MariaDB von Medulla vergeben:"),
    "hint_fed_priv_old": ("(MariaDB older than 10.5.2: GRANT SUPER instead)",
                          "(MariaDB antérieur à 10.5.2 : GRANT SUPER à la place)",
                          "(MariaDB anterior a 10.5.2: GRANT SUPER en su lugar)",
                          "(MariaDB älter als 10.5.2: stattdessen GRANT SUPER)"),
    "fed_using_root": ("Federated server created as root through the local socket",
                       "Serveur fédéré créé en root via le socket local",
                       "Servidor federado creado como root mediante el socket local",
                       "Föderierter Server als root über den lokalen Socket angelegt"),
    "fedtables_kept": ("{n} existing federated table(s) kept: they now point to the new server",
                       "{n} table(s) fédérée(s) existante(s) conservée(s) : elles pointent désormais vers le nouveau serveur",
                       "{n} tabla(s) federada(s) existente(s) conservada(s): ahora apuntan al nuevo servidor",
                       "{n} vorhandene föderierte Tabelle(n) beibehalten: sie zeigen jetzt auf den neuen Server"),
    "fedtables_created_list": ("{n} missing federated table(s) created: {list}",
                               "{n} table(s) fédérée(s) manquante(s) créée(s) : {list}",
                               "{n} tabla(s) federada(s) faltante(s) creada(s): {list}",
                               "{n} fehlende föderierte Tabelle(n) angelegt: {list}"),
    "fedtable_not_federated": ("xmppmaster.{table} exists with engine {engine} (not FEDERATED): left untouched",
                               "xmppmaster.{table} existe avec le moteur {engine} (pas FEDERATED) : laissée telle quelle",
                               "xmppmaster.{table} existe con el motor {engine} (no FEDERATED): se deja intacta",
                               "xmppmaster.{table} existiert mit Engine {engine} (nicht FEDERATED): unverändert gelassen"),
    "apply_stopped": ("Stopped: nothing else was modified (configuration files and saas_application untouched)",
                      "Arrêt : rien d'autre n'a été modifié (fichiers de configuration et saas_application intacts)",
                      "Detenido: no se ha modificado nada más (archivos de configuración y saas_application intactos)",
                      "Abgebrochen: sonst wurde nichts geändert (Konfigurationsdateien und saas_application unverändert)"),
    "cryptkey_glpi10_empty": ("GLPI 10: glpi_crypt_key is empty in saas_application — fix mode will set it to {value}",
                              "GLPI 10 : glpi_crypt_key est vide dans saas_application — le mode correction y inscrira {value}",
                              "GLPI 10: glpi_crypt_key está vacío en saas_application — el modo corrección escribirá {value}",
                              "GLPI 10: glpi_crypt_key ist in saas_application leer — der Korrekturmodus trägt {value} ein"),
    "cryptkey_glpi10_ok": ("GLPI 10: the crypt key is not used (only needed for GLPI 11)",
                           "GLPI 10 : la clé de chiffrement n'est pas utilisée (nécessaire seulement pour GLPI 11)",
                           "GLPI 10: la clave de cifrado no se usa (solo necesaria para GLPI 11)",
                           "GLPI 10: der Schlüssel wird nicht verwendet (nur für GLPI 11 nötig)"),
    "cryptkey_glpi10_info": ("GLPI 10: no crypt key needed ({value} is stored if nothing is set)",
                             "GLPI 10 : pas de clé de chiffrement à saisir ({value} sera inscrit si rien n'est défini)",
                             "GLPI 10: no hace falta clave de cifrado (se guarda {value} si no hay nada)",
                             "GLPI 10: kein Schlüssel nötig ({value} wird eingetragen, falls nichts gesetzt ist)"),
    "type_api_empty": ("type_api is missing or empty in saas_application — fix mode will set it to {value}",
                       "type_api est absent ou vide dans saas_application — le mode correction y inscrira {value}",
                       "type_api falta o está vacío en saas_application — el modo corrección escribirá {value}",
                       "type_api fehlt oder ist leer in saas_application — der Korrekturmodus trägt {value} ein"),
    "type_api_other": ("type_api = {value} in saas_application (Medulla uses {expected}): left unchanged",
                       "type_api = {value} dans saas_application (Medulla utilise {expected}) : laissé tel quel",
                       "type_api = {value} en saas_application (Medulla usa {expected}): se deja igual",
                       "type_api = {value} in saas_application (Medulla nutzt {expected}): unverändert"),
    "type_api_ok": ("type_api = {value} in saas_application", "type_api = {value} dans saas_application",
                    "type_api = {value} en saas_application", "type_api = {value} in saas_application"),
    "saas_row_inserted": ("Missing setting {name} added to saas_application",
                          "Paramètre {name} absent : ajouté dans saas_application",
                          "Parámetro {name} ausente: añadido a saas_application",
                          "Fehlende Einstellung {name} in saas_application ergänzt"),
    "restart_all_ok": ("Medulla services restarted ({cmd})", "Services Medulla redémarrés ({cmd})",
                       "Servicios de Medulla reiniciados ({cmd})", "Medulla-Dienste neu gestartet ({cmd})"),
    "restart_all_ko": ("{cmd} failed ({err}): restarting the services one by one",
                       "Échec de {cmd} ({err}) : redémarrage des services un par un",
                       "Fallo de {cmd} ({err}): reinicio de los servicios uno a uno",
                       "{cmd} fehlgeschlagen ({err}): Dienste werden einzeln neu gestartet"),
    "plan_restart_all": ("restart all Medulla services with {cmd}", "redémarrage de tous les services Medulla via {cmd}",
                         "reinicio de todos los servicios de Medulla con {cmd}", "Neustart aller Medulla-Dienste mit {cmd}"),
    "medulla_version": ("Medulla version: {v}", "Version de Medulla : {v}", "Versión de Medulla: {v}",
                        "Medulla-Version: {v}"),
    "medulla_version_unknown": ("Medulla version not found (mmc-agent package, {file})",
                                "Version de Medulla introuvable (paquet mmc-agent, {file})",
                                "Versión de Medulla no encontrada (paquete mmc-agent, {file})",
                                "Medulla-Version nicht gefunden (Paket mmc-agent, {file})"),
    "machines_cols_missing": ("local_glpi_machines lacks the columns required since Medulla 5.6.6 ({cols}) — installed: {v}",
                              "local_glpi_machines n'a pas les colonnes requises depuis Medulla 5.6.6 ({cols}) — installée : {v}",
                              "local_glpi_machines no tiene las columnas requeridas desde Medulla 5.6.6 ({cols}) — instalada: {v}",
                              "local_glpi_machines fehlen die seit Medulla 5.6.6 nötigen Spalten ({cols}) — installiert: {v}"),
    "machines_cols_ok": ("local_glpi_machines has the columns required by Medulla {v}",
                         "local_glpi_machines a les colonnes requises par Medulla {v}",
                         "local_glpi_machines tiene las columnas requeridas por Medulla {v}",
                         "local_glpi_machines hat die von Medulla {v} benötigten Spalten"),
    "machines_cols_added": ("local_glpi_machines recreated with the Medulla {v} definition (added: {cols})",
                            "local_glpi_machines recréée avec la définition de Medulla {v} (ajout : {cols})",
                            "local_glpi_machines recreada con la definición de Medulla {v} (añadido: {cols})",
                            "local_glpi_machines mit der Definition von Medulla {v} neu angelegt (ergänzt: {cols})"),
    "glpi_computers_cols_missing": ("glpi_computers in GLPI lacks columns read by Medulla through federation: {cols}",
                                    "glpi_computers dans GLPI n'a pas des colonnes lues par Medulla via la fédération : {cols}",
                                    "glpi_computers en GLPI no tiene columnas que Medulla lee mediante la federación: {cols}",
                                    "glpi_computers in GLPI fehlen Spalten, die Medulla über die Föderation liest: {cols}"),
    "fedserver_created": ("Federated server itsm_federated created", "Serveur fédéré itsm_federated créé",
                          "Servidor federado itsm_federated creado", "Föderierter Server itsm_federated angelegt"),
    "fedtables_created": ("{n} federated tables created", "{n} tables fédérées créées",
                          "{n} tablas federadas creadas", "{n} föderierte Tabellen angelegt"),
    "federated_apply_ko": ("Federated setup failed: {err}", "Échec de la création des objets fédérés : {err}",
                           "Fallo al crear los objetos federados: {err}",
                           "Anlage der föderierten Objekte fehlgeschlagen: {err}"),
    "saas_row_missing": ("Setting {name} missing from admin.saas_application (not created)",
                         "Paramètre {name} absent de admin.saas_application (non créé)",
                         "Parámetro {name} ausente de admin.saas_application (no creado)",
                         "Einstellung {name} fehlt in admin.saas_application (nicht angelegt)"),
    "saas_updated": ("admin.saas_application updated", "admin.saas_application mis à jour",
                     "admin.saas_application actualizado", "admin.saas_application aktualisiert"),
    "saas_update_ko": ("admin.saas_application update failed: {err}",
                       "Échec de la mise à jour de admin.saas_application : {err}",
                       "Fallo al actualizar admin.saas_application: {err}",
                       "Aktualisierung von admin.saas_application fehlgeschlagen: {err}"),
    "restart_ok": ("{svc} restarted", "{svc} redémarré", "{svc} reiniciado", "{svc} neu gestartet"),
    "restart_ko": ("{svc} restart failed: {err}", "Échec du redémarrage de {svc} : {err}",
                   "Fallo al reiniciar {svc}: {err}", "Neustart von {svc} fehlgeschlagen: {err}"),
    "reconf_confirm": ("Ask the {n} Medulla agent(s) to reconfigure now?",
                       "Demander la reconfiguration des {n} agent(s) Medulla maintenant ?",
                       "¿Solicitar ahora la reconfiguración de los {n} agente(s) Medulla?",
                       "Neukonfiguration der {n} Medulla-Agenten jetzt anfordern?"),
    "reconf_skipped": ("Agent reconfiguration skipped — to do it later:",
                       "Reconfiguration des agents ignorée — pour la faire plus tard :",
                       "Reconfiguración de los agentes omitida — para hacerla más tarde:",
                       "Neukonfiguration der Agenten übersprungen — später nachholen mit:"),
    "reconf_ok": ("{n} agent(s) marked for reconfiguration", "{n} agent(s) marqué(s) pour reconfiguration",
                  "{n} agente(s) marcado(s) para reconfiguración", "{n} Agent(en) zur Neukonfiguration markiert"),
    "reconf_ko": ("Cannot mark agents for reconfiguration: {err}",
                  "Impossible de marquer les agents pour reconfiguration : {err}",
                  "No se pueden marcar los agentes para reconfiguración: {err}",
                  "Agenten können nicht zur Neukonfiguration markiert werden: {err}"),
    "regen_ok": ("Medulla agent installer regenerated without the inventory agent",
                 "Installeur de l'agent Medulla régénéré sans agent d'inventaire",
                 "Instalador del agente Medulla regenerado sin agente de inventario",
                 "Medulla-Agent-Installer ohne Inventar-Agent neu erstellt"),
    "regen_ko": ("Agent regeneration failed (code {rc}), see {log}",
                 "Échec de la régénération de l'agent (code {rc}), voir {log}",
                 "Fallo al regenerar el agente (código {rc}), ver {log}",
                 "Neuerstellung des Agenten fehlgeschlagen (Code {rc}), siehe {log}"),
    "postcheck_title": ("Full check after applying the configuration", "Vérification complète après application",
                        "Verificación completa tras la aplicación", "Vollständige Prüfung nach der Anwendung"),
    "apply_had_failures": ("{n} error(s) occurred while applying the configuration (see above)",
                           "{n} erreur(s) pendant l'application de la configuration (voir plus haut)",
                           "{n} error(es) durante la aplicación de la configuración (ver arriba)",
                           "{n} Fehler beim Anwenden der Konfiguration (siehe oben)"),

    # Summary
    "summary_title": ("Summary", "Bilan", "Resumen", "Zusammenfassung"),
    "sum_passed": ("{n} passed", "{n} réussi(s)", "{n} correcto(s)", "{n} bestanden"),
    "sum_warned": ("{n} warning(s)", "{n} avertissement(s)", "{n} advertencia(s)", "{n} Warnung(en)"),
    "sum_failed": ("{n} failed", "{n} échec(s)", "{n} fallo(s)", "{n} fehlgeschlagen"),
    "sum_failures": ("Failures:", "Échecs :", "Fallos:", "Fehler:"),
    "sum_warnings": ("Warnings:", "Avertissements :", "Advertencias:", "Warnungen:"),
    "all_good": ("No failed check.", "Aucune vérification en échec.", "Ninguna verificación fallida.",
                 "Keine fehlgeschlagene Prüfung."),
    "some_failed": ("Some checks failed.", "Des vérifications ont échoué.", "Algunas verificaciones fallaron.",
                    "Einige Prüfungen sind fehlgeschlagen."),
}

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