#!/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_V16.py   (the version is in the file name and in SCRIPT_VERSION)
# History:
#   V1  initial version (check / fix modes)
#   V2  forward URL checks are blocking (empty POST), default URL from core.url_base,
#       explicit restart / need_reconf, inventory substitute log
#   V3  logs analysis, simulated agent PROLOG, GLPI version, inventory auth_required, --collect,
#       every configuration file read (all substitutes, injection mode, DB TLS, .generation_options)
#   V4  check mode is strictly read-only: the setting_name cleaning of saas_application is done by fix
#       mode only; a guard refuses any write while check mode runs
#   V5  aligned with the Medulla installer (Ansible 5.6.6): numbered substitutes (inv2, reg3...),
#       substitutes on other servers (substituteconf), read-only GLPI keeps the inventory forward and needs
#       no API login, empty glpi_crypt_key on GLPI 10, 'mysql' federated wrapper fallback
#   V6  API client found by its App-Token (external GLPI: the client is not necessarily named MMC,
#       see install_from_ansible.py --external-itsm-apiapptoken)
#   V7  first real-server run: substitutes neither enabled nor running are ignored; without root, what cannot be
#       verified is a warning (privileges, mysql.servers, unreadable files); database errors of other modules
#       are no longer taken for GLPI errors; logs of other modules listed apart; API URL of saas_application
#       tested; legacy glpiinventory forward endpoint accepted; grouped file-permission warning
#   V8  logs: DEBUG / INFO lines ignored, bare "initSession" no longer an API error, past log events are
#       warnings; GLPI Self-Service profile check; admin / glpi plugin load errors dated against mmc-agent start
#   V9  admin plugin of mmc-agent checked (admin.ini then admin.ini.local: database, tables, schema version);
#       the database error logged just before a plugin load failure is shown as its cause
#   V10 rotated logs read (<log>.1 at rotation_time, <log>.YYYY-MM-DD for mmc-agent); cause of a plugin load
#       failure: strictly before it (milliseconds) and about the same module
#   V11 admin plugin not loaded after an automatic schema update, schema up to date now: "restart mmc-agent"
#   V12 admin plugin still not loaded after a restart: installed code inspected (activate() returning None when
#       already activated, other activators), and the mmc-agent.log lines before the failure shown;
#       --verbose / -v: files read, SQL queries, HTTP calls, commands (secrets masked), Python traceback
#   V13 « Plugin admin not loaded » explained: mmc-agent loads the admin plugin twice, the first load succeeds
#       (seen in the log, and in the installed loadPlugins); tokens shown by their length only
#   V14 check of configuration files readable by everyone removed (Medulla default rights, not ITSM-specific)
#   V15 saas_application API URL that works is left alone (check: information; fix: kept); HTTP API URL: information
#   V16 missing Self-Service profile (check and logs): information; « Plugin X not loaded » of plugins other than
#       admin / glpi moved to the other modules' errors
# 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 (files, databases, services, GLPI).
          Mistyped setting_name in admin.saas_application (e.g. "glpi_root_user_token ") are only
          reported; fix mode renames them. --collect only creates the diagnostic archive in ~.
  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.

Fix mode only restarts the services reading the modified files, and never marks the agents for
reconfiguration (need_reconf) unless asked: interactively (default: No) or with --restart / --reconf.

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 glob
import gzip
import json
import io
import ipaddress
import os
import re
import shutil
import socket
import subprocess
import sys
import tarfile
import tempfile
import time
import zlib
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


def install_http_trace():
    """--verbose: log every HTTP call made through requests (method, URL, status, time, start of the body)."""
    if requests is None:
        return
    original = requests.Session.request

    def traced(self, method, url, *a, **kw):
        for hk, hv in (kw.get("headers") or {}).items():
            if re.search(r"token|authorization", hk, re.I):
                register_secret(str(hv).split(" ", 1)[-1])
        if kw.get("auth"):
            for part in kw["auth"] if isinstance(kw["auth"], tuple) else ():
                register_secret(part)
        t0 = time.time()
        try:
            resp = original(self, method, url, *a, **kw)
        except Exception as e:
            vlog(f"HTTP {method.upper()} {url} -> {type(e).__name__}: {e}")
            raise
        body = resp.content[:300]
        try:
            body = gzip.decompress(resp.content)[:300]
        except Exception:
            pass
        vlog(f"HTTP {method.upper()} {url} -> {resp.status_code} {resp.reason}, {(time.time() - t0) * 1000:.0f} ms, "
             f"{len(resp.content)} bytes" + (f" (redirected: {' → '.join(h.url for h in resp.history)})"
                                             if resp.history else "")
             + f" | {' '.join(body.decode('utf-8', 'replace').split())[:200]}")
        return resp
    requests.Session.request = traced
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")   # minimum set; see glpi_services()
MMC_AGENT_CONF = "/etc/mmc/agent/config.ini"
ADMIN_INI = "/etc/mmc/plugins/admin.ini"      # mmc-agent plugin admin: holds saas_application (GLPI API settings)
ADMIN_SQL_DIRS = ("/usr/share/doc/pulse2/contrib/admin/sql", "/usr/share/doc/pulse2-common/contrib/admin/sql")
# Tables the admin plugin maps at start (pulse2/database/admin): saas_* and this list
ADMIN_TABLES = ("saas_application", "providers", "magic_link", "medulla_update_availability", "acl_categories",
                "acl_profiles", "acl_profile_features", "version")
# Messages logged (ERROR or WARNING) when a Medulla database module fails to start (mmc/database)
RX_DB_INIT_CAUSE = re.compile(r"The table .* does not exists|Error when initializing mappers|database version error|"
                              r"Can't connect to database|Failed to (create database engine|prepare automap base)|"
                              r"Database check failed|does not have a version in the database|"
                              r"does not use the lastest schema|Error while execute script|version conflict")
# Master substitute types: short name used in agent_master_substitute_<short><n>.ini -> long name used in
# pulse-xmpp-master-substitute-<long><n>.service. The Medulla installer (Ansible substitute_agent role) adds
# numbered substitutes (inv2, reg3...) by copying agent_master_substitute_<short>.ini and the <long> service.
SUBST_TYPES = {"inv": "inventory", "reg": "registration", "mast": "master", "dma": "diskmastering",
               "asse": "assessor", "depl": "deployment", "log": "logger", "mon": "monitoring",
               "reconf": "reconfigurator", "subs": "subscription", "upd": "updates"}
# Values used by a substitute when [glpidatabase] does not set them (lib/configuration.py readConfglpi)
SUBST_GLPIDB_DEFAULTS = {"glpi_dbhost": "localhost", "glpi_dbport": "3306", "glpi_dbname": "glpi",
                         "glpi_dbuser": "mmc", "glpi_dbpasswd": "mmc"}
INJECTION_MODES = {"forward": "forward", "current": "forward", "legacy": "forward",
                   "module": "module", "glpi_xml_sync": "module", "both": "both"}

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)
INV_LOG = "/var/log/mmc/master-inv.log"   # log of pulse-xmpp-master-substitute-inventory
INV_LOG_TAIL = 4 * 1024 * 1024            # bytes read at the end of INV_LOG
INV_LOG_RECENT = 20                       # inventories considered "recent" in INV_LOG
# Answers of the inventory forward URL to an empty POST meaning "right endpoint":
# GLPI 10/11 front/inventory.php answers 400 (empty request); 2xx / 405 also prove the endpoint exists.
FORWARD_OK_CODES = (400, 405)
SUBST_USER_AGENT = "siveo-injector"       # default [glpi] user_agent of the inventory substitute
SIMU_DEVICEID = "medulla-itsm-check"       # DEVICEID of the simulated PROLOG (no computer is created)
MMC_LOG_DIR = "/var/log/mmc"              # every Medulla log (mmc-agent.log, master-*.log, ...)
LOG_TAIL = 8 * 1024 * 1024                # bytes read at the end of each log
LOG_SINCE_HOURS = 24                      # default analysis window (--since)
LOG_TOP = 8                               # unknown error signatures shown
# GLPI logs, only readable when GLPI runs on the Medulla server itself
GLPI_LOG_DIRS = ("/var/log/glpi", "/var/lib/glpi/_log", "/var/lib/glpi/files/_log", "/var/www/glpi/files/_log",
                 "/var/www/html/glpi/files/_log", "/usr/share/glpi/files/_log")
SECRET_KEYS = re.compile(r"(passw|passwd|password|token|secret|crypt_key|apikey|api_key)", re.I)

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
SCRIPT_VERSION = "V16"

# ─────────────────────────────────────────────────────────────────────────────
# i18n
# ─────────────────────────────────────────────────────────────────────────────
VERBOSE = False         # --verbose / -v: every file, query, HTTP call and command is shown (secrets masked)


_VLOGGED = set()          # files already reported by --verbose


def vlog(msg):
    """Debug line, only with --verbose."""
    if VERBOSE:
        print("      " + _c("2", "· " + mask_secrets(str(msg))[:400]), flush=True)


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
        self.facts = {}                  # label -> value, shown at the top of the summary

    def fact(self, label, value):
        self.facts[label] = value

    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"  {'Script':<12}: medulla_itsm {SCRIPT_VERSION}")
        for label, value in self.facts.items():
            print(f"  {label:<12}: {value}")
        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")
                for sec in cp.sections():
                    for key, val in cp.items(sec, raw=True):
                        if SECRET_KEYS.search(key):
                            register_secret(val)
                if path not in _VLOGGED:
                    _VLOGGED.add(path)
                    vlog(f"read {path}")
            except (configparser.Error, OSError, UnicodeDecodeError) as e:
                vlog(f"unreadable {path}: {e}")
        elif path not in _VLOGGED:
            _VLOGGED.add(path)
            vlog(f"absent {path}")
    return cp


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


def ini_source(base, section, key):
    """Where a substitute / plugin value comes from: '.local', the base file, or the built-in default."""
    if ini_get(read_ini(base + ".local"), section, key, None) is not None:
        return os.path.basename(base) + ".local"
    if ini_get(read_ini(base), section, key, None) is not None:
        return os.path.basename(base)
    return "default"


_SVC_CACHE = {}


def service_state(svc):
    """(installed, enabled, active) of a systemd unit; (None, None, None) without systemctl."""
    if svc not in _SVC_CACHE:
        if not shutil.which("systemctl"):
            _SVC_CACHE[svc] = (None, None, None)
        else:
            en = run(["systemctl", "is-enabled", svc], timeout=20).stdout.strip()
            ac = run(["systemctl", "is-active", svc], timeout=20).stdout.strip()
            installed = en not in ("", "not-found") or ac in ("active", "activating", "reloading")
            _SVC_CACHE[svc] = (installed, en in ("enabled", "static", "alias", "indirect"), ac == "active")
    return _SVC_CACHE[svc]


_SUBS_CACHE = None


def substitutes():
    """Every master substitute configured on this server (agent_master_substitute_<short><n>.ini), read
    exactly as the substitute reads it (its .ini, then .ini.local; substitute defaults when [glpidatabase]
    does not set a key). Numbered substitutes (inv2, reg3...) are included."""
    global _SUBS_CACHE
    if _SUBS_CACHE is not None:
        return _SUBS_CACHE
    names = set()
    for path in glob.glob(f"{SUBST_DIR}/agent_master_substitute_*.ini") + \
            glob.glob(f"{SUBST_DIR}/agent_master_substitute_*.ini.local"):
        names.add(re.sub(r"\.ini(\.local)?$", "", os.path.basename(path))[len("agent_master_substitute_"):])
    out = []
    for name in sorted(names, key=lambda n: (re.sub(r"\d+$", "", n), int(re.sub(r"^\D+", "", n) or 0))):
        m = re.fullmatch(r"([a-z]+?)(\d*)", name)
        if not m or m.group(1) not in SUBST_TYPES:
            continue
        kind, num = m.group(1), m.group(2)
        svc = f"pulse-xmpp-master-substitute-{SUBST_TYPES[kind]}{num}"
        base = f"{SUBST_DIR}/agent_master_substitute_{name}.ini"
        cp = read_ini(base, base + ".local")
        plugins = [x.strip() for x in ini_get(cp, "global", "activate_plugin", "").split(",") if x.strip()]
        glpidb = {k: ini_get(cp, "glpidatabase", k, d) for k, d in SUBST_GLPIDB_DEFAULTS.items()}
        installed, enabled, active = service_state(svc)
        out.append({"short": name, "kind": kind, "service": svc, "base": base, "local": base + ".local",
                    "uses_glpi": "glpi" in plugins, "plugins": plugins, "glpidb": glpidb,
                    "glpidb_src": {k: ini_source(base, "glpidatabase", k) for k in SUBST_GLPIDB_DEFAULTS},
                    "glpi": dict(cp.items("glpi")) if cp.has_section("glpi") else {},
                    "jid": ini_get(cp, "connection", "jidmastersubstitute", ""),
                    "logfile": ini_get(cp, "global", "logfile", ""),
                    "installed": installed, "enabled": enabled, "active": active})
    _SUBS_CACHE = out
    return out


def reset_substitutes_cache():
    """After fix mode wrote the files / restarted the services: read them again."""
    global _SUBS_CACHE
    _SUBS_CACHE = None
    _SVC_CACHE.clear()


def inv_substitutes():
    """Inventory substitutes of this server that are installed (or whose state is unknown); the active one
    first. Every one of them forwards inventories with its own [glpi] section."""
    subs = [s for s in substitutes() if s["kind"] == "inv" and s["installed"] is not False]
    return sorted(subs, key=lambda s: (s["active"] is not True, s["enabled"] is not True, s["short"]))


def primary_inv():
    subs = inv_substitutes()
    return subs[0] if subs else None


def inv_setting(sub, key, default=""):
    """[glpi] value of an inventory substitute, with the substitute's own default."""
    defaults = {"enable_forward": "True", "inventory_injection_mode": "forward", "user_agent": SUBST_USER_AGENT,
                "url_to_forward": "", "inventory_plugin": ""}
    return (sub or {}).get("glpi", {}).get(key, defaults.get(key, default))


def remote_substitutes():
    """Substitutes declared in xmppmaster.substituteconf whose JID is not configured on this server:
    they run elsewhere and read their own [glpidatabase] / url_to_forward there. Returns [(jid, type)]."""
    try:
        conn = db_connect(database="xmppmaster", **medulla_db_settings())
        try:
            rows = db_query(conn, "SELECT DISTINCT jidsubtitute, type FROM substituteconf")
        finally:
            conn.close()
    except DBError:
        return []
    def user(jid):
        return str(jid).split("@")[0].split("/")[0].lower()
    # "master" is the main master agent (mmc-agent on this server); JIDs are compared on their local part
    # because the XMPP domain is written differently in the base files and in the database.
    local = {user(s["jid"]) for s in substitutes() if s["jid"]} | {"master"}
    return sorted({(str(j), str(t)) for j, t in rows if user(j) not in local})


def service_started(svc):
    """Last start of a systemd service (local time), or None."""
    if not shutil.which("systemctl"):
        return None
    out = run(["systemctl", "show", "-p", "ActiveEnterTimestamp", "--value", svc], timeout=20).stdout
    m = re.search(r"(\d{4}-\d\d-\d\d) (\d\d:\d\d:\d\d)", out or "")
    if not m:
        return None
    try:
        return datetime.datetime.strptime(f"{m.group(1)} {m.group(2)}", "%Y-%m-%d %H:%M:%S")
    except ValueError:
        return None


def sub_in_use(sub):
    """A substitute is in use when its service is enabled or running (or when systemctl is unavailable).
    The Medulla installer does not deploy every substitute (e.g. diskmastering): an installed unit that is
    neither enabled nor running is not in use and is neither checked nor restarted."""
    return sub["installed"] is not False and not (sub["enabled"] is False and sub["active"] is False)


def glpi_substitutes(include_unused=False):
    """Substitutes that load the glpi plugin (they read [glpidatabase]); by default only those in use.
    include_unused: also the installed ones not in use (their file is kept consistent by fix mode)."""
    return [s for s in substitutes() if s["uses_glpi"] and s["installed"] is not False
            and (include_unused or sub_in_use(s))]


def unused_glpi_substitutes():
    return [s for s in glpi_substitutes(include_unused=True) if not sub_in_use(s)]


def glpi_services():
    """mmc-agent + the services of every substitute reading the GLPI database (restart / check list)."""
    found = [s["service"] for s in glpi_substitutes()]
    return ["mmc-agent"] + (found or list(SERVICES[1:]))


def injection_mode(value):
    return INJECTION_MODES.get((value or "forward").strip().lower(), "forward")


def configured_log_files():
    """Log files declared in the configuration (substitutes' logfile, mmc-agent handlers)."""
    paths = {s["logfile"] for s in substitutes() if s["logfile"]}
    for path in (MMC_AGENT_CONF, MMC_AGENT_CONF + ".local"):
        try:
            with open(path, encoding="utf-8", errors="replace") as fh:
                paths.update(re.findall(r"args\s*=\s*\(\s*[\"']([^\"']+\.log)[\"']", fh.read()))
        except OSError:
            pass
    return sorted(x.replace("@localstatedir@", "/var") for x in paths)


def inv_log_path():
    return (primary_inv() or {}).get("logfile") or INV_LOG


def generation_disables_inventory():
    """True / False from .generation_options (--disable-inventory), None when the file does not exist."""
    try:
        with open(GEN_OPTIONS, encoding="utf-8", errors="replace") as fh:
            return "--disable-inventory" in fh.read().split()
    except OSError:
        return None


def db_ssl_kwargs(ssl):
    """mysql.connector TLS options from glpi.ini dbsslca / dbsslcert / dbsslkey."""
    if not ssl:
        return {}
    kw = {"ssl_ca": ssl.get("ca") or None, "ssl_cert": ssl.get("cert") or None, "ssl_key": ssl.get("key") or None}
    return {k: v for k, v in kw.items() if v}


def glpi_connect(p, database=True):
    """Connection to the external GLPI database with the Medulla parameters (TLS if glpi.ini enables it)."""
    return db_connect(p.db_host, p.db_port, p.db_user, p.db_pass, p.db_name if database else None,
                      ssl=getattr(p, "db_ssl", None))


def root_cmd():
    """Command to run this very script again as root, in check mode."""
    return f"sudo {sys.argv[0] or 'medulla_itsm.py'} --mode check"


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, ssl=None):
    register_secret(password)
    vlog(f"SQL connect {user}@{host}:{port}/{database or ''}" + (" (TLS)" if ssl else ""))
    kw = dict(host=host, port=int(port), user=user, password=password or "",
              connection_timeout=TIMEOUT, **db_ssl_kwargs(ssl))
    if database:
        kw["database"] = database
    return mysql.connector.connect(**kw)


def can_create_server(conn, raise_errors=False):
    """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:
        if raise_errors:
            raise
        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


class _CliCursor:
    """Minimal DB-API cursor running each statement through the `mysql` client as root (unix socket).
    Used when mysql.connector cannot authenticate root (MariaDB unix_socket plugin)."""

    def __init__(self, conn):
        self.conn, self._rows, self.with_rows = conn, [], True

    def execute(self, sql, args=()):
        if args:
            parts = sql.split("%s")
            sql = parts[0] + "".join(sql_literal(a) + rest for a, rest in zip(args, parts[1:]))
        cmd = [self.conn.client, "--protocol=socket", "-u", "root", "-N", "-B", "--raw"]
        if self.conn.socket:
            cmd += ["--socket", self.conn.socket]
        if self.conn.database:
            cmd += ["-D", self.conn.database]
        try:
            # SQL on stdin: the federated server password never shows up in `ps`
            res = subprocess.run(cmd, input=sql + ";\n", stdout=subprocess.PIPE, stderr=subprocess.PIPE,
                                 universal_newlines=True, timeout=120)
        except (OSError, subprocess.TimeoutExpired) as e:
            raise mysql.connector.Error(msg=str(e))
        if res.returncode != 0:
            raise mysql.connector.Error(msg=(res.stderr or "mysql client error").strip())
        self._rows = [tuple(None if f == "NULL" else f for f in line.split("\t"))
                      for line in res.stdout.splitlines()]

    def fetchall(self):
        rows, self._rows = self._rows, []
        return rows

    def close(self):
        pass


class CliConnection:
    def __init__(self, client, socket_path, database):
        self.client, self.socket, self.database = client, socket_path, database

    def cursor(self):
        return _CliCursor(self)

    def commit(self):
        pass

    def close(self):
        pass


ADMIN_ERRORS = []      # why each admin connection attempt failed (shown in the diagnostics)


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 with mysql.connector;
    3) otherwise root through the `mysql` client (supports MariaDB unix_socket authentication,
       which mysql.connector does not).
    Returns (conn, account). Raises DBError / PermissionError when none works."""
    del ADMIN_ERRORS[:]
    s = medulla_db_settings()
    conn = db_connect(database=database, **s)
    if can_create_server(conn):
        return conn, s["user"]
    ADMIN_ERRORS.append(f"{s['user']}: no SUPER / FEDERATED ADMIN ON *.*")
    try:
        socket_path = db_query(conn, "SELECT @@socket")[0][0]
    except DBError:
        socket_path = None
    conn.close()
    if s["host"] not in ("localhost", "127.0.0.1", "::1"):
        ADMIN_ERRORS.append(f"root: Medulla DB host is {s['host']} (not local)")
    elif os.geteuid() != 0:
        ADMIN_ERRORS.append("root: script not run as root")
    else:
        if 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()
                ADMIN_ERRORS.append("root (python): no SUPER / FEDERATED ADMIN")
            except DBError as e:
                ADMIN_ERRORS.append(f"root (python): {short(e, 160)}")
        client = shutil.which("mariadb") or shutil.which("mysql")
        if client:
            cli = CliConnection(client, socket_path, database)
            try:
                if can_create_server(cli, raise_errors=True):
                    return cli, "root"
                ADMIN_ERRORS.append("root (mysql client): no SUPER / FEDERATED ADMIN")
            except DBError as e:
                ADMIN_ERRORS.append(f"root (mysql client): {short(e, 160)}")
        else:
            ADMIN_ERRORS.append("root (mysql client): mysql / mariadb command not found")
    raise PermissionError(T("fed_priv_ko", user=s["user"]))


def db_query(conn, sql, args=None):
    cur = conn.cursor()
    t0 = time.time()
    try:
        cur.execute(sql, args or ())
        rows = cur.fetchall() if cur.with_rows else []
        vlog(f"SQL {' '.join(sql.split())[:200]}{f' [{len(args)} value(s), not shown]' if args else ''} -> {len(rows)} row(s), "
             f"{(time.time() - t0) * 1000:.0f} ms")
        return rows
    except Exception as e:
        vlog(f"SQL {' '.join(sql.split())[:200]} -> ERROR {e}")
        raise
    finally:
        cur.close()


def saas_canonical(name):
    """Name without invisible characters and case: used only to recognise a mistyped setting_name."""
    return re.sub(r"[\s\u00a0\u200b\ufeff]+", "", str(name or "")).lower()


def read_saas_rows():
    """All rows of admin.saas_application, as stored. Returns (rows, error)."""
    try:
        conn = db_connect(database="admin", **medulla_db_settings())
        try:
            return [(str(n or ""), v) for n, v in db_query(conn, "SELECT setting_name, setting_value "
                                                                  "FROM saas_application")], None
        finally:
            conn.close()
    except DBError as e:
        return [], short(e)


def saas_misnamed(rows):
    """Rows whose setting_name differs from the expected one only by case / spaces / invisible characters.
    Medulla (pulse2/database/admin get_CONNECT_API) indexes the rows by their exact name: it does not
    find them. Returns [(stored_name, expected_name)] for expected names that have no exact row."""
    exact = {n for n, _ in rows}
    out = []
    for name, _ in rows:
        expected = next((e for e in SAAS_DESCRIPTIONS if saas_canonical(e) == saas_canonical(name)), None)
        if expected and name != expected and expected not in exact:
            out.append((name, expected))
    return out


def read_saas():
    """{setting_name: value} exactly as Medulla sees it: exact names, values stripped (get_CONNECT_API)."""
    rows, err = read_saas_rows()
    return {n: v.strip() for n, v in rows if isinstance(v, str)}, err


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 forward_url_for(base):
    """Inventory forward URL of a GLPI 10/11 whose public URL is base (core.url_base)."""
    return f"{(base or '').rstrip('/')}/front/inventory.php" if base else ""


def api_session_ok(url, p):
    """True if the GLPI REST API at `url` opens a session with the configured App-Token + user token (the way
    mmc-agent calls it). Read-only: the session is closed right away."""
    if requests is None or not (url and p.app_token and p.user_token):
        return False
    headers = {"App-Token": p.app_token, "Authorization": "user_token " + p.user_token}
    try:
        resp = requests.get(url.rstrip("/") + "/initSession", headers=headers, verify=p.verify_ssl, timeout=TIMEOUT)
        token = resp.json().get("session_token") if resp.status_code == 200 else None
    except Exception:
        return False
    if token:
        try:
            requests.get(url.rstrip("/") + "/killSession", headers={"App-Token": p.app_token, "Session-Token": token},
                         verify=p.verify_ssl, timeout=TIMEOUT)
        except Exception:
            pass
    return bool(token)


def same_url(a, b):
    return (a or "").rstrip("/").lower() == (b or "").rstrip("/").lower()


def forward_urls(value):
    """url_to_forward may hold several comma-separated URLs (the substitute posts to each)."""
    return [u.strip() for u in (value or "").split(",") if u.strip()]


def read_tail(path, size):
    """Last `size` bytes of a text file, as lines (the first, probably cut, line is dropped)."""
    with open(path, "rb") as fh:
        fh.seek(0, os.SEEK_END)
        total = fh.tell()
        fh.seek(max(0, total - size))
        lines = fh.read().decode("utf-8", errors="replace").splitlines()
    return lines[1:] if total > size and lines else lines


_RX_MASK = [re.compile(r"((?:passw\w*|token|secret|crypt_key)\s*[=:]\s*)(?:\"[^\"]*\"|'[^']*'|[^\s,;)]+)", re.I),
            re.compile(r"(PASSWORD\s+)('[^']*')", re.I),
            re.compile(r"(user_token\s+)(\S+)", re.I),
            re.compile(r"(App-Token['\"]?\s*[:=]\s*['\"]?)([A-Za-z0-9]{16,})", re.I),
            re.compile(r"(://[^/:@\s]+:)([^@\s]+)(@)")]


_RX_MASK.append(re.compile(r"(\"[^\"]*(?:passw|token|secret|crypt_key|apikey|api_key)[^\"]*\"\s*:\s*)(\"[^\"]*\")", re.I))
_RX_MASK.append(re.compile(r"((?:Authorization|Session-Token|App-Token)['\"]?\s*[:=]\s*['\"]?)([^'\",}\s]+(?: [^'\",}\s]+)?)", re.I))
KNOWN_SECRETS = set()      # every password / token / key value the script has read or been given


def register_secret(value):
    """Remember a secret value so that it is masked wherever it appears (verbose output, logs, archive)."""
    value = str(value or "").strip().strip("'\"")
    if len(value) >= 4 and value.upper() not in ("REPLACE", "NONE", "TRUE", "FALSE"):
        KNOWN_SECRETS.add(value)


def mask_secrets(text):
    """Hide passwords / tokens that may appear in log lines or configuration files."""
    for value in sorted(KNOWN_SECRETS, key=len, reverse=True):
        if value in text:
            text = text.replace(value, "********")
    for rx in _RX_MASK:
        text = rx.sub(lambda m: m.group(1) + "********" + (m.group(3) if rx.groups >= 3 else ""), text)
    return text


_RX_LOG_TIME = (re.compile(r"^(\d{4}-\d\d-\d\d)[ T](\d\d:\d\d:\d\d)(?:[,.](\d{1,6}))?"),  # 2026-11-24 08:47:37,123
                re.compile(r"^\[(\d{4}-\d\d-\d\d) (\d\d:\d\d:\d\d)(?:[,.](\d{1,6}))?"))  # GLPI: [2026-11-24 08:47:37]


def log_time(line):
    for rx in _RX_LOG_TIME:
        m = rx.match(line)
        if m:
            try:
                ts = datetime.datetime.strptime(f"{m.group(1)} {m.group(2)}", "%Y-%m-%d %H:%M:%S")
                frac = m.group(3)
                return ts.replace(microsecond=int(frac.ljust(6, "0"))) if frac else ts
            except ValueError:
                return None
    return 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):
    t0 = time.time()
    try:
        res = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
                             universal_newlines=True, timeout=timeout)
    except (OSError, subprocess.TimeoutExpired) as e:
        res = subprocess.CompletedProcess(cmd, 1, "", str(e))
    vlog(f"run {' '.join(cmd)} -> rc={res.returncode}, {(time.time() - t0) * 1000:.0f} ms"
         + (f", {' '.join((res.stdout or res.stderr or '').split())[:160]}" if VERBOSE else ""))
    return res


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 = glpi_connect(p)
    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, inv_mode="forward", db_ssl=None)

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

    def __setattr__(self, name, value):
        if SECRET_KEYS.search(name) or name in ("db_pass", "api_pass"):
            register_secret(value)
        object.__setattr__(self, name, value)


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:
        version = ""
        if mysql is not None:
            p, _ = load_current_params()
            try:
                conn = glpi_connect(p)
                try:
                    rows = db_query(conn, "SELECT value FROM glpi_configs WHERE context='core' AND name='version'")
                    version = rows[0][0] if rows else ""
                finally:
                    conn.close()
            except DBError:
                pass
        print("  " + green(T("state_connected", host=host, port=port, db=name)) + "  —  " +
              (f"GLPI {version}" if version else T("glpi_version_unreachable")))
    else:
        print("  " + yellow(T("state_not_connected", host=host or T("not_set"), file=GLPI_INI_LOCAL)))
    return connected


def api_root(api_url):
    """https://glpi/apirest.php or https://glpi/api.php/v1 -> https://glpi"""
    return re.sub(r"/(apirest\.php|api\.php(/v\d+)?)/?$", "", (api_url or "").rstrip("/"))


def load_current_params():
    """Read the current Medulla configuration: everything that can be known without asking.
    Sources, in order of trust: glpi.ini(.local) (mmc-agent), admin.saas_application, the substitutes'
    configuration (agent_master_substitute_*.ini(.local)), registeryagent.ini, the client inventory.ini
    and .generation_options."""
    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().lower() in ("1", "true", "yes")
    if ini_get(cp, "main", "dbsslenable", "0").strip().lower() in ("1", "true", "yes"):
        p.db_ssl = {"ca": ini_get(cp, "main", "dbsslca"), "cert": ini_get(cp, "main", "dbsslcert"),
                    "key": ini_get(cp, "main", "dbsslkey")}
    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")

    saas, err = read_saas()
    rows, _ = read_saas_rows()
    for stored, expected in saas_misnamed(rows):
        value = dict(rows).get(stored)
        saas.setdefault(expected, value.strip() if isinstance(value, str) else "")
    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"], "")
    p.api_url = p.api_url or saas.get(SAAS_KEYS["api_url"], "")

    # Inventory: the (active) inventory substitute of this server; the others are compared in check_config
    inv = primary_inv()
    if inv:
        p.inv_forward = inv_setting(inv, "enable_forward").strip().lower() in ("true", "1", "yes")
        p.inv_forward_url = inv_setting(inv, "url_to_forward")
        p.inv_plugin = inv_setting(inv, "inventory_plugin") or "glpiinventory"
        p.inv_mode = injection_mode(inv_setting(inv, "inventory_injection_mode"))
    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"
    disabled = generation_disables_inventory()
    if disabled is not None:
        p.inv_agent_disabled = disabled

    # GLPI web URL: first source that has it
    first_url = [u for u in forward_urls(p.inv_forward_url) if "/front/inventory.php" in u][:1]
    for candidate in (ini_get(cp, "authentication_glpi", "baseurl"),
                      ini_get(cp, "main", "glpi_computer_uri").split("/front/")[0],
                      api_root(p.api_url),
                      first_url[0].split("/front/inventory.php")[0] if first_url else ""):
        if candidate and v_url(candidate) is None:
            p.url = candidate.rstrip("/")
            break

    # GLPI database: glpi.ini is the reference; a substitute already pointing to an external GLPI
    # completes what glpi.ini does not give (e.g. a half-done previous configuration).
    ext = [s for s in glpi_substitutes() if s["glpidb"]["glpi_dbhost"].lower() != "localhost"]
    if ext and (not p.db_host or p.db_host.lower() == "localhost"):
        db = ext[0]["glpidb"]
        p.db_host, p.db_port, p.db_name = db["glpi_dbhost"], to_int(db["glpi_dbport"], 3306), db["glpi_dbname"]
        p.db_user, p.db_pass = db["glpi_dbuser"], db["glpi_dbpasswd"]
    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"******** ({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)]
    # The API settings (admin.saas_application, local Medulla DB) are needed even when the GLPI DB is read-only
    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_mode", p.inv_mode))
    if p.db_ssl:
        rows.append(("lbl_db_ssl", p.db_ssl.get("ca") or T("yes")))
    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, intro=None):
    rep.section(T("sec_params"))
    if intro:
        rep.info(intro)
    show_params(p)
    ok = True
    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)]
    # API login / password: only written by the Medulla installer when GLPI is writeable (purge of machines);
    # the tokens in saas_application are always needed.
    if not p.readonly:
        required += [("lbl_api_user", p.api_user), ("lbl_api_pass", p.api_pass)]
    required += [("lbl_app_token", p.app_token), ("lbl_user_token", p.user_token)]
    if p.inv_forward and p.inv_mode != "module":
        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
# ─────────────────────────────────────────────────────────────────────────────
def config_summary_lines():
    """Everything read from the configuration, one line per value, with its source; secrets masked.
    Shown in check mode and saved into the diagnostic archive."""
    out = []
    cp = read_ini(GLPI_INI, GLPI_INI_LOCAL)

    def src(section, key):
        return ini_source(GLPI_INI, section, key)
    out.append(("title", GLPI_INI_LOCAL + "  (mmc-agent, plugin glpi)"))
    for section, keys in (("main", ("disable", "dbdriver", "dbhost", "dbport", "dbname", "dbuser", "dbpasswd",
                                    "dbreadonly", "dbsslenable", "dbsslca", "glpi_computer_uri", "active_profiles",
                                    "check_db_enable", "hide_itsm_link")),
                          ("webservices", ("glpi_base_url", "glpi_username", "glpi_password", "purge_machine")),
                          ("authentication_glpi", ("baseurl", "doauth")),
                          ("provisioning_glpi", ("exclude", "profiles_order"))):
        for key in keys:
            value = ini_get(cp, section, key, None)
            if value is None:
                continue
            shown = "********" if SECRET_KEYS.search(key) and value else value
            out.append(("value", f"[{section}] {key}", shown, src(section, key)))
    saas, err = read_saas()
    out.append(("title", "admin.saas_application"))
    if err:
        out.append(("value", "-", err, ""))
    for name in SAAS_DESCRIPTIONS:
        value = saas.get(name)
        if value is None:
            out.append(("value", name, T("not_set"), ""))
        else:
            shown = value if name in ("glpi_url_base_api", "type_api") or not value else \
                (CRYPT_KEY_GLPI10 if value == CRYPT_KEY_GLPI10 else f"******** ({len(value)})")
            out.append(("value", name, shown, ""))
    for sub in substitutes():
        state = {True: "active", False: "inactive", None: "?"}[sub["active"]]
        if sub["installed"] is False:
            state = "not installed"
        elif sub["enabled"] is False:
            state += ", disabled"
        out.append(("title", f"{os.path.basename(sub['local'])}  ({sub['service']}: {state})"))
        out.append(("value", "activate_plugin", ", ".join(sub["plugins"]) or "-", ""))
        if sub["uses_glpi"]:
            db = sub["glpidb"]
            out.append(("value", "[glpidatabase]",
                        f"{db['glpi_dbuser']}@{db['glpi_dbhost']}:{db['glpi_dbport']}/{db['glpi_dbname']}",
                        ", ".join(sorted(set(sub["glpidb_src"].values())))))
        if sub["kind"] == "inv":
            for key in ("enable_forward", "url_to_forward", "inventory_injection_mode", "inventory_plugin",
                        "user_agent", "dbreadonly", "inventory_verbose", "xmldumpactive", "enable_forward_ocsserver"):
                if key in sub["glpi"]:
                    out.append(("value", f"[glpi] {key}", sub["glpi"][key], ini_source(sub["base"], "glpi", key)))
        if sub["jid"]:
            out.append(("value", "jidmastersubstitute", sub["jid"], ""))
        if sub["logfile"]:
            out.append(("value", "logfile", sub["logfile"], ""))
    remote = remote_substitutes()
    if remote:
        out.append(("title", T("cfg_remote_title")))
        for jid, kind in remote:
            out.append(("value", kind, jid, ""))
    reg = read_ini(REGAGENT_INI, REGAGENT_INI + ".local")
    out.append(("title", os.path.basename(REGAGENT_INI) + ".local"))
    out.append(("value", "check_uuidinventory", ini_get(reg, "parameters", "check_uuidinventory", "False"),
                ini_source(REGAGENT_INI, "parameters", "check_uuidinventory")))
    out.append(("title", T("cfg_client_agent")))
    out.append(("value", CLIENT_INV_INI + " agent",
                ini_get(read_ini(CLIENT_INV_INI), "parameters", "agent", "") or "fusioninventory", ""))
    disabled = generation_disables_inventory()
    out.append(("value", GEN_OPTIONS + " --disable-inventory",
                T("not_set") if disabled is None else yesno(disabled), ""))
    return out


def print_config_summary(lines, printer=print):
    for line in lines:
        if line[0] == "title":
            printer(f"    {bold(line[1])}")
        else:
            _, key, value, src = line
            printer(f"      {key:<34} = {value}" + (f"   {dim('(' + src + ')')}" if src else ""))


# Known error signatures in the Medulla / GLPI logs: (key, regex, "fail" | "warn")
# key -> messages log_<key> (diagnosis) and hint_log_<key> (what to do)
LOG_PATTERNS = (
    ("forward_404", r"Inventory forward to \S+ rejected: HTTP 404| - ERROR - 404\s*$", "fail"),
    ("forward_401", r"Inventory forward to \S+ rejected: HTTP 401| - ERROR - 401\s*$", "fail"),
    ("forward_403", r"Inventory forward to \S+ rejected: HTTP 403| - ERROR - 403\s*$|Inventory is disabled", "fail"),
    ("forward_5xx", r"Inventory forward to \S+ rejected: HTTP 5\d\d| - ERROR - 5\d\d\s*$", "fail"),
    ("forward_net", r"Inventory forward to \S+ failed:", "fail"),
    ("tls", r"CERTIFICATE_VERIFY_FAILED|SSLError|certificate verify failed", "fail"),
    ("federated", r"foreign data source|itsm_federated|error 10000 from storage engine|\b1429\b|\b1430\b", "fail"),
    ("db_denied", r"Access denied for user|\(1045|\b1045\b", "fail"),
    ("db_unreachable", r"Can't connect to (MySQL|MariaDB) server|\(2003|Lost connection to (MySQL|MariaDB)|"
                       r"MySQL server has gone away|\(2013", "fail"),
    ("db_schema", r"Unknown column|\(1054|doesn't exist|\(1146", "fail"),
    ("api", r"ERROR_WRONG_APP_TOKEN|ERROR_APP_TOKEN_PARAMETERS_MISSING|ERROR_GLPI_LOGIN|ERROR_SESSION_TOKEN|"
            r"ERROR_LOGIN_PARAMETERS_MISSING|ERROR_NOT_ALLOWED_IP", "fail"),
    ("plugin", r"is disabled or not installed, the inventory will be sent but not saved", "fail"),
    ("selfservice", r"Unable to find Self-Service profile in GLPI", "info"),
    ("mmc_plugin", r"Plugin (admin|glpi) not loaded|Plugin (admin|glpi): an error occurred", "warn"),
    ("no_uuid", r"no inventory is found for the address Macs|Injection of inventory for machine .* failed", "warn"),
)
# Keys only counted when the error concerns GLPI: the same database / TLS errors also come from other Medulla
# modules (updates, deployment...) that have nothing to do with the ITSM connection.
LOG_NEEDS_GLPI_CONTEXT = {"db_denied", "db_unreachable", "db_schema", "tls"}
RX_GLPI_CONTEXT = re.compile(r"glpi|itsm|local_glpi_", re.I)
RX_LOG_ERROR = re.compile(r"\b(ERROR|CRITICAL|FATAL|Traceback)\b|glpi(php|sql)log\.(ERROR|CRITICAL|ALERT|EMERGENCY)"
                          r"|PHP (Fatal|Warning)|SQL Error")
# Log level written after the date: "<date> - LEVEL - msg" (substitutes), "<date> #thread LEVEL msg" (mmc-agent),
# "[<date>] channel.LEVEL: msg" (GLPI). DEBUG / INFO lines are never errors, whatever words their data contain.
RX_LOG_LEVEL = re.compile(r"^\[?\d{4}-\d\d-\d\d[ T][\d:,.+]+\]?\s+(?:#\d+\s+)?(?:-\s+)?(?:\w+\.)?"
                          r"(DEBUG|INFO|NOTICE|WARNING|WARN|ERROR|CRITICAL|FATAL|ALERT|EMERGENCY)\b")


PY_ROOTS = ("/usr/lib/python3/dist-packages", "/usr/local/lib/python3/dist-packages")


def inspect_admin_activation():
    """Read-only look at the INSTALLED Medulla code (not the repository): does AdminDatabase.activate() return
    None when the database is already activated (the admin plugin then takes it for a failure), and which other
    modules activate AdminDatabase or use the "database" configuration backend (that activates it too)?"""
    roots = [r for r in PY_ROOTS + tuple(x for x in sys.path if x.endswith("-packages"))
             if os.path.isfile(os.path.join(r, "pulse2", "database", "admin", "__init__.py"))]
    if not roots:
        return None
    root = roots[0]
    out = {"root": root, "returns_none": False, "plugin_tests_not": False, "activators": [],
           "conditional": [], "db_backend_users": [], "double_load": False}
    try:
        with open(os.path.join(root, "mmc", "agent.py"), encoding="utf-8", errors="replace") as fh:
            agent = fh.read()
        # loadPlugins() puts admin right after base without removing it from its alphabetical place
        out["double_load"] = 'plugins.insert(1, "admin")' in agent and 'plugins.remove("admin")' not in agent
    except OSError:
        pass
    try:
        with open(os.path.join(root, "pulse2", "database", "admin", "__init__.py"), encoding="utf-8",
                  errors="replace") as fh:
            out["returns_none"] = bool(re.search(r"if self\.is_activated:\s*\n\s*return None", fh.read()))
        with open(os.path.join(root, "mmc", "plugins", "admin", "__init__.py"), encoding="utf-8",
                  errors="replace") as fh:
            out["plugin_tests_not"] = "if not AdminDatabase().activate(" in fh.read()
    except OSError:
        pass
    rx_direct = re.compile(r"AdminDatabase\(\)\s*\.activate\(")
    rx_cond = re.compile(r"_admin_db\.activate\(")             # PluginConfig, only with backend="database"
    rx_backend = re.compile(r"backend\s*=\s*['\"]database['\"]")
    for sub in ("mmc", "pulse2"):
        for path in glob.glob(os.path.join(root, sub, "**", "*.py"), recursive=True):
            if path.endswith(os.path.join("mmc", "plugins", "admin", "__init__.py")):
                continue
            try:
                with open(path, encoding="utf-8", errors="replace") as fh:
                    for n, line in enumerate(fh, 1):
                        code = line.split("#", 1)[0]
                        where = f"{os.path.relpath(path, root)}:{n}"
                        if rx_direct.search(code):
                            out["activators"].append(where)
                        elif rx_cond.search(code):
                            out["conditional"].append(where)
                        elif rx_backend.search(code) and not re.search(r"def |if backend|==\s*['\"]database", code):
                            out["db_backend_users"].append(where)
            except OSError:
                continue
    return out


def mmc_agent_log_level():
    """Level of mmc-agent.log ([handler_hand01] level of config.ini, then config.ini.local)."""
    cp = read_ini(MMC_AGENT_CONF, MMC_AGENT_CONF + ".local")
    return (ini_get(cp, "handler_hand01", "level", "INFO") or "INFO").strip().upper()


def rotated_logs(path, since):
    """The log and its rotated copies written since `since`: <log>.N (Medulla substitutes rotate at
    [parameters] rotation_time by copying to <log>.1) and <log>.YYYY-MM-DD (mmc-agent, midnight)."""
    files = [path]
    for other in glob.glob(glob.escape(path) + ".*"):
        if other.endswith((".gz", ".bz2", ".xz", ".zip")):
            continue
        try:
            if os.path.isfile(other) and os.path.getmtime(other) >= since.timestamp():
                files.append(other)
        except OSError:
            pass
    return files


def read_log_window(path, since, size):
    """Lines of a log and of its rotated copies within the window (oldest copy first)."""
    lines = []
    copies = [f for f in rotated_logs(path, since) if f != path]
    copies.sort(key=lambda f: os.path.getmtime(f))
    for f in copies + [path]:
        part = read_tail(f, size)
        vlog(f"log {f}: {len(part)} line(s) read")
        lines += part
    return lines


_RX_CAUSE_MODULE = re.compile(r"for the (\w+) module|module (\w+)\b|'(\w+)' database|Database '(\w+)'|"
                              r"contrib/(\w+)/sql", re.I)


def cause_module(line):
    """Module a database start message is about (admin, security...), or None when it names none."""
    m = _RX_CAUSE_MODULE.search(line)
    return next((g.lower() for g in m.groups() if g), None) if m else None


def log_level(line):
    m = RX_LOG_LEVEL.match(line)
    return m.group(1) if m else None


def log_signature(text):
    """Error line without date, numbers, ids, quoted values: groups identical errors together."""
    t = re.sub(r"^\[?\d{4}-\d\d-\d\d[ T][\d:,.+]*\]?\s*(-\s*)?", "", text)
    t = re.sub(r"'[^']{0,200}'|\"[^\"]{0,200}\"", "'…'", t)
    t = re.sub(r"\b[0-9a-f]{8,}\b|\b\d+\b", "#", t)
    t = re.sub(r"\S+@\S+|\b\d+\.\d+\.\d+\.\d+\b", "…", t)
    return " ".join(t.split())[:160]


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()
        self.unreadable_logs = []
        self.db_init_causes = []        # (ts, source, line) of database start errors seen in the logs
        self.admin_schema_ok = None     # set by check_admin_plugin: admin database schema up to date now
        self.admin_code = None          # set by check_admin_plugin: inspection of the installed code
        self.raw_logs = {}              # source -> lines (mmc-agent.log only), for the context of a failure

    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"), T("hint_run_as_root", cmd=root_cmd()))
        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))
            r.fact("Medulla", 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):
                if os.geteuid() != 0:
                    # root (local socket) is only tried when the script runs as root: not verifiable here
                    r.warn(T("fed_priv_unverified", user=s["user"]), T("hint_run_as_root", cmd=root_cmd()))
                else:
                    r.fail(T("fed_priv_ko", user=s["user"]),
                           list(ADMIN_ERRORS) +
                           [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 = glpi_connect(p, database=False)
        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
            # Not `conn.database = ...`: the pure-Python mysql.connector (Debian python3-mysql.connector)
            # sends `USE <name>` unquoted, which fails on names such as glpi-agglo (error 1064).
            db_query(conn, "USE `" + p.db_name.replace("`", "``") + "`")
            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 IN ('enabled_inventory','auth_required'))")
        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
        dbv_full = self.glpi_cfg.get("core.dbversion") or ""
        r.fact("GLPI", version + (f" (schema {dbv_full.split('@')[0]})" if dbv_full and dbv_full.split("@")[0] != version
                                  else ""))
        if self.glpi_cfg.get("core.url_base"):
            r.fact("GLPI URL", self.glpi_cfg["core.url_base"])
        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"))
        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
        if self.missing_views and self.glpi_major in SQL_FILES:
            self.print_sql_notice()
        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"))
        lacking = [x for x in ("CREATE VIEW", "DROP") if not has(x)]
        if lacking:
            r.info(T("grants_no_create_view", list=", ".join(lacking)))

    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]))
                r.fact(T("fact_plugin"), f"{p.inv_plugin} {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 not same_url(base, p.url):
            r.warn(T("url_base_mismatch", glpi=base, medulla=p.url),
                   [T("hint_url_base_fix", url=base), T("hint_url_base_glpi")])
        elif base:
            r.ok(T("url_base_ok", url=base))
        if True:  # API used by Medulla whatever the read-only setting
            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"))
            # GLPI inventory authentication (basic_auth / client_credentials): the substitute sends no
            # Authorization header, so GLPI answers 401 to every forwarded inventory.
            auth = (cfg.get("inventory.auth_required") or "").strip()
            if auth and auth.lower() not in ("none", "0"):
                r.fail(T("inventory_auth_ko", mode=auth), [T("hint_inventory_auth")])
            elif auth:
                r.ok(T("inventory_auth_ok"))

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

    def _check_selfservice_profile(self):
        """Medulla creates the GLPI accounts of its users (mmc/support/apirest/glpi create_user) with the profile
        whose name, without spaces / dashes / case, is "selfservice". Another name (e.g. a profile renamed
        "Demandeur") makes every creation fail with "Unable to find Self-Service profile in GLPI"."""
        r = self.rep
        try:
            rows = db_query(self.conn, "SELECT name, interface FROM glpi_profiles")
        except DBError as e:
            r.warn(T("check_error", err=short(e)))
            return
        def norm(x):
            return str(x or "").lower().replace(" ", "").replace("-", "")
        found = [str(n) for n, _ in rows if norm(n) in ("selfservice", "self_service")]
        if found:
            r.ok(T("selfservice_ok", name=found[0]))
            return
        helpdesk = [str(n) for n, i in rows if str(i) == "helpdesk"]
        # information only: the account creation fails but the console login goes on, and a user created with
        # Self-Service gets no Medulla rights anyway unless Self-Service is in [provisioning_glpi] profiles_order
        r.info(T("selfservice_missing", list=", ".join(helpdesk) or "-"))

    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):
        """API client used by Medulla. A local GLPI installed by Medulla has a client named MMC; for an external
        GLPI the App-Token is given at install time (install_from_ansible.py --external-itsm-apiapptoken) and
        may belong to any client: it is found by its App-Token first, then by the name MMC."""
        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")
        except DBError as e:
            r.warn(T("check_error", err=short(e)))
            return
        by_token = [x for x in rows if p.app_token and classify_token(x[4])[1] == p.app_token]
        by_name = [x for x in rows if x[0] == MMC_API_CLIENT]
        if by_token:
            chosen = by_token[0]
            r.ok(T("apiclient_found_token", name=chosen[0]))
        elif by_name:
            chosen = by_name[0]
            if len(by_name) > 1:
                r.warn(T("mmc_client_multiple", n=len(by_name), name=MMC_API_CLIENT))
        else:
            # No client named MMC and the configured App-Token is not stored in clear: the API test decides
            names = ", ".join(str(x[0]) for x in rows) or "-"
            r.warn(T("apiclient_not_identified", name=MMC_API_CLIENT, list=names), T("hint_apiclient_not_identified"))
            return
        name, active, start, end, app_token = chosen
        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=name), 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
        r.section(T("sec_cryptkey"))
        if p.glpi_major == 10:
            # Medulla reads glpi_crypt_key only for GLPI 11 (plugins/glpi/database_110.py); the installer
            # writes an empty value for GLPI 10.
            r.ok(T("cryptkey_glpi10_ok"))
            return
        err = v_cryptkey(p.crypt_key) if p.crypt_key else T("cryptkey_missing")
        if p.glpi_major is None:
            if err:
                r.warn(T("cryptkey_version_unknown"), T("cryptkey_howto"))
                return
        elif err:
            shown = p.crypt_key if p.crypt_key and len(p.crypt_key) <= 16 else ""
            r.fail(T("cryptkey_glpi11_placeholder", v=self.glpi_version or p.glpi_major, value=shown)
                   if shown else T("cryptkey_glpi11_required", v=self.glpi_version or p.glpi_major, err=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, method="get", **kw):
        host = urlparse(url).hostname
        verify = self.p.verify_ssl and host not in self.ssl_failed
        try:
            return requests.request(method, 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, method, **kw)
        except requests.exceptions.RequestException as e:
            return None, short(e)

    def glpi_url_base(self):
        """core.url_base of GLPI (glpi_configs), or "" when the GLPI database was not read."""
        return (self.glpi_cfg.get("core.url_base") or "").rstrip("/")

    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)
        base = self.glpi_url_base()
        hint_base = T("hint_glpi_url_base", url=base) if base and not same_url(base, p.url) else None
        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))
        elif resp.status_code == 404 or resp.status_code >= 500:
            # 404: GLPI is not installed at this path (e.g. /glpi/ added while GLPI is at the site root)
            r.fail(T("url_http_code", url=p.url, code=resp.status_code),
                   hint_base or T("hint_url_not_glpi"), fix="params")
        else:
            r.warn(T("url_http_code", url=p.url, code=resp.status_code), hint_base)

    @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 _api_targets(self):
        """API URL(s) to test: the parameter, plus — in check mode — glpi_url_base_api of saas_application when it
        differs (mmc-agent calls the API with that one)."""
        urls = [(self.p.api_url.rstrip("/"), "glpi.ini.local")]
        if CHECK_ONLY:
            saas_url = (read_saas()[0].get(SAAS_KEYS["api_url"]) or "").rstrip("/")
            if saas_url and not same_url(saas_url, urls[0][0]):
                urls.append((saas_url, "admin.saas_application"))
        return urls

    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
        base = (p.url or "").rstrip("/")
        targets = self._api_targets()
        for api, source in targets:
            if len(targets) > 1:
                r.info(T("api_target", url=api, src=source))
            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"))
            if api.startswith("http://") and base.startswith("https://"):
                r.info(T("api_url_http", url=api, src=source))
            resp, err = self._http(api)
            if resp is None:
                r.fail(T("url_unreachable", url=api, err=err), T("hint_firewall_web"))
                continue
            r.ok(T("url_reachable", url=api, code=resp.status_code))
            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 _post_forward(self, url):
        """Empty POST, as the inventory substitute does (requests.post, redirects followed as requests does
        by default, TLS always verified). Returns (resp, err, tls_err)."""
        tls_err = None
        try:
            return requests.post(url, data=b"", timeout=TIMEOUT, verify=True,
                                 headers={"Content-Type": "application/x-gzip"}), None, None
        except requests.exceptions.SSLError as e:
            tls_err = short(e, 160)
        except requests.exceptions.RequestException as e:
            return None, short(e), None
        # TLS rejected: the substitute would fail too; get the HTTP answer anyway for the diagnosis
        try:
            return requests.post(url, data=b"", timeout=TIMEOUT, verify=False,
                                 headers={"Content-Type": "application/x-gzip"}), None, tls_err
        except requests.exceptions.RequestException as e:
            return None, short(e), tls_err

    @staticmethod
    def _forward_code_ok(code):
        return 200 <= code < 300 or code in FORWARD_OK_CODES

    def check_forward(self):
        r, p = self.rep, self.p
        if not p.inv_forward:
            return
        r.section(T("sec_forward"))
        if p.inv_mode == "module":
            r.info(T("forward_module_mode"))
            return
        if not p.inv_forward_url:
            r.fail(T("param_missing", name=T("lbl_inv_url")), fix="params")
            return
        for url in self._forward_targets():
            self._check_forward_url(url)

    def _forward_targets(self):
        """URL(s) to test: those of the parameters, plus — in check mode — those of the other inventory
        substitutes of this server (inv2, inv3... each forwards with its own url_to_forward)."""
        urls = forward_urls(self.p.inv_forward_url)
        if CHECK_ONLY:
            for sub in inv_substitutes():
                if (inv_setting(sub, "enable_forward").lower() in ("true", "1", "yes")
                        and injection_mode(inv_setting(sub, "inventory_injection_mode")) != "module"):
                    urls += [u for u in forward_urls(inv_setting(sub, "url_to_forward"))
                             if not any(same_url(u, x) for x in urls)]
        return urls

    def _check_forward_url(self, url):
        r, p = self.rep, self.p
        expected = forward_url_for(self.glpi_url_base())
        resp, err, tls_err = self._post_forward(url)
        if tls_err:
            r.fail(T("forward_tls_ko", url=url, err=tls_err), [T("hint_forward_tls"), T("hint_ssl_ca")])
        if resp is None:
            r.fail(T("url_unreachable", url=url, err=err), T("hint_firewall_web"))
            return
        history = [h.status_code for h in resp.history]
        if history and resp.request is not None and resp.request.method != "POST":
            # 301/302/303 turn the POST into a GET: the inventory body is lost
            r.fail(T("forward_redirect", url=url, codes=", ".join(map(str, history)), to=resp.url),
                   T("hint_forward_redirect", url=resp.url), fix="params")
        elif self._forward_code_ok(resp.status_code):
            r.ok(T("forward_post_ok", url=url, code=resp.status_code))
        elif resp.status_code in (401, 403):
            # GLPI answers before reading the body: inventory authentication required (401) or disabled (403)
            r.fail(T("forward_post_ko", url=url, code=resp.status_code),
                   T("hint_inventory_auth") if resp.status_code == 401 else T("hint_enable_inventory"))
        else:
            hints = [T("hint_forward_code", code=resp.status_code)]
            probable = expected or forward_url_for(p.url)   # GLPI's own URL first, else the web URL
            if probable and not same_url(probable, url):
                eresp, _, _ = self._post_forward(probable)
                if eresp is not None and self._forward_code_ok(eresp.status_code):
                    hints.insert(0, T("hint_forward_probable_ok", url=probable, code=eresp.status_code))
                else:
                    hints.insert(0, T("hint_forward_probable", url=probable))
            if re.search(r"/(glpi|itsm-ng)/front/inventory\.php$", url) and probable and not same_url(probable, url):
                hints.append(T("hint_forward_installer_default"))
            r.fail(T("forward_post_ko", url=url, code=resp.status_code), hints, fix="params")
        works = self._forward_code_ok(resp.status_code) and not history
        if expected and not same_url(expected, url):
            if works and re.search(r"/plugins/glpiinventory/front/plugin_fusioninventory\.communication\.php$", url):
                r.info(T("forward_url_legacy", expected=expected))
            elif works:
                r.info(T("forward_url_differs_ok", expected=expected))
            else:
                r.warn(T("forward_url_differs", url=url, expected=expected))
        elif not expected and "front/inventory.php" not in url:
            r.warn(T("forward_url_hint", url=forward_url_for(p.url)))

    @staticmethod
    def _decode_reply(content):
        """GLPI compresses its answer like the request (gzip / zlib); returns readable text."""
        for fn in (gzip.decompress, zlib.decompress):
            try:
                return fn(content).decode("utf-8", errors="replace")
            except Exception:
                continue
        return (content or b"").decode("utf-8", errors="replace")

    def simulate_forward(self):
        """Send what an agent sends first (PROLOG), exactly the way the inventory substitute does:
        same User-Agent, gzip body, same headers, requests.post defaults (redirects followed, TLS verified).
        A PROLOG carries no inventory: GLPI creates no computer; it only answers with the inventory frequency."""
        r, p = self.rep, self.p
        if not p.inv_forward or not p.inv_forward_url or p.inv_mode == "module":
            return
        r.section(T("sec_simulate"))
        user_agent = inv_setting(primary_inv(), "user_agent") or SUBST_USER_AGENT
        body = ("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<REQUEST><DEVICEID>"
                f"{SIMU_DEVICEID}</DEVICEID><QUERY>PROLOG</QUERY></REQUEST>").encode()
        headers = {"User-Agent": user_agent, "Pragma": "no-cache", "Content-Type": "Application/x-gzip"}
        r.info(T("simu_what", ua=user_agent, deviceid=SIMU_DEVICEID))
        for url in self._forward_targets():
            try:
                resp = requests.post(url, headers=headers, data=gzip.compress(body, compresslevel=9),
                                     timeout=TIMEOUT * 3)
            except requests.exceptions.SSLError as e:
                r.fail(T("simu_ko", url=url, code="TLS", err=short(e, 160)), [T("hint_forward_tls"), T("hint_ssl_ca")])
                continue
            except requests.exceptions.RequestException as e:
                r.fail(T("simu_ko", url=url, code="-", err=short(e, 160)), T("hint_firewall_web"))
                continue
            reply = " ".join(self._decode_reply(resp.content).split())
            m = re.search(r"<ERROR>(.*?)</ERROR>", reply, re.S)
            err = m.group(1) if m else ""
            if not err:
                try:
                    data = json.loads(reply)
                    err = data.get("message", "") if isinstance(data, dict) and data.get("status") == "error" else ""
                except ValueError:
                    pass
            freq = re.search(r"<PROLOG_FREQ>(\d+)</PROLOG_FREQ>", reply)
            if resp.status_code == 200 and (freq or "<RESPONSE>" in reply or '"status":"ok"' in reply.replace(" ", "")):
                r.ok(T("simu_ok", url=url, freq=freq.group(1) if freq else "?"))
                continue
            hints = []
            if resp.status_code == 401:
                hints.append(T("hint_inventory_auth"))
            elif resp.status_code == 403:
                hints.append(T("hint_enable_inventory"))
            elif resp.status_code == 404:
                hints.append(T("hint_forward_probable", url=forward_url_for(self.glpi_url_base() or p.url)))
            elif resp.status_code >= 500:
                hints.append(T("hint_glpi_server_logs"))
            if not err:
                err = re.sub(r"<[^>]+>", " ", reply)
                err = " ".join(err.split())[:200] or "-"
            r.fail(T("simu_ko", url=url, code=resp.status_code, err=short(err, 200)), hints, fix="params"
                   if resp.status_code == 404 else None)

    def check_forward_log(self):
        """Check mode: what the inventory substitute actually got back from GLPI (its logfile).
        Works with both log formats of plugin_resultinventory.py:
          before 1.19: '<date> - ERROR - 404' then '... forward_done=True' (even on failure)
          since 1.19 : '... Inventory forward to <url> rejected: HTTP 404 ...' / '... forward_done=False'"""
        r, p = self.rep, self.p
        if not p.inv_forward:
            return
        r.section(T("sec_forward_log"))
        log = inv_log_path()
        try:
            # current log and its copy made by the daily rotation (<log>.1): the last inventories may be there
            lines = read_log_window(log, datetime.datetime.now() - datetime.timedelta(days=2), INV_LOG_TAIL)
        except OSError as e:
            r.info(T("inv_log_unreadable", file=log, err=short(e, 120)))
            return
        rx_date = re.compile(r"^(\d{4}-\d\d-\d\d[ T]\d\d:\d\d:\d\d)")
        rx_old = re.compile(r" - ERROR - (\d{3})\s*$")
        rx_new = re.compile(r"Inventory forward to (\S+) (?:rejected: HTTP (\d{3})|failed: (.*))")
        rx_inj = re.compile(r"Inventory injection mode=(\w+) forward_done=(\w+)")
        inventories = []                          # [(date, error or None)]
        pending = None
        for line in lines:
            m = rx_new.search(line)
            if m:
                pending = f"HTTP {m.group(2)}" if m.group(2) else short(m.group(3), 80)
                continue
            m = rx_old.search(line)
            if m and not 200 <= int(m.group(1)) < 300:
                pending = f"HTTP {m.group(1)}"
                continue
            m = rx_inj.search(line)
            if m:
                if m.group(1) in ("forward", "both"):
                    if pending is None and m.group(2) == "False":
                        pending = "forward_done=False"
                    d = rx_date.match(line)
                    inventories.append((d.group(1) if d else "?", pending))
                pending = None
        if not inventories:
            r.info(T("inv_log_none", file=log))
            return
        recent = inventories[-INV_LOG_RECENT:]
        failed = [e for _, e in recent if e]
        last_date, last_err = inventories[-1]
        if last_err:
            codes = ", ".join(sorted(set(failed)))
            r.fail(T("inv_log_last_ko", date=last_date, err=last_err, n=len(failed), total=len(recent),
                     codes=codes, file=log),
                   [T("hint_inv_log", file=log), T("hint_inv_log_after_fix")], fix="params")
        elif failed:
            r.warn(T("inv_log_some_ko", n=len(failed), total=len(recent), codes=", ".join(sorted(set(failed))),
                     date=last_date), T("hint_inv_log", file=log))
        else:
            r.ok(T("inv_log_ok", total=len(recent), date=last_date))

    # ── Logs ─────────────────────────────────────────────────────────────────
    def _log_sources(self, since):
        """Yield (source name, lines) for every log worth reading on the Medulla server."""
        paths = set(glob.glob(os.path.join(MMC_LOG_DIR, "*.log"))) | set(configured_log_files())
        for path in sorted(paths):
            if not os.path.isfile(path):
                continue
            try:
                if os.path.getmtime(path) < since.timestamp() and len(rotated_logs(path, since)) == 1:
                    continue                    # nothing written in the window
                yield os.path.basename(path), read_log_window(path, since, LOG_TAIL)
            except OSError:
                self.unreadable_logs.append(path)
        if shutil.which("journalctl"):
            for svc in glpi_services():
                res = run(["journalctl", "-u", svc, "--since", since.strftime("%Y-%m-%d %H:%M:%S"),
                           "-p", "err", "--no-pager", "-q", "-o", "short-iso"], timeout=60)
                if res.returncode == 0 and res.stdout.strip():
                    # short-iso: 2026-11-24T08:47:37+0100 host unit[pid]: message
                    lines = [re.sub(r"^(\S+?)T(\d\d:\d\d:\d\d)\S*\s+\S+\s+", r"\1 \2 - ERROR - ", ln)
                             for ln in res.stdout.splitlines()]
                    yield f"journal:{svc}", lines
        for d in GLPI_LOG_DIRS:
            for path in sorted(glob.glob(os.path.join(d, "*.log"))):
                try:
                    if os.path.getmtime(path) >= since.timestamp():
                        yield "glpi:" + os.path.basename(path), read_tail(path, LOG_TAIL)
                except OSError:
                    pass

    def _is_itsm_log(self, source):
        """Logs involved in the ITSM link: mmc-agent, the substitutes loading the glpi plugin (their logfile),
        their systemd journal, and GLPI's own logs."""
        if source.startswith("glpi:") or source == "mmc-agent.log":
            return True
        if source.startswith("journal:"):
            return source.split(":", 1)[1] in glpi_services()
        files = {os.path.basename(s["logfile"]) for s in glpi_substitutes(include_unused=True) if s["logfile"]}
        return source in (files or {"master-inv.log", "master-reg.log", "master-mast.log"})

    def _admin_loaded_before(self, when, seconds=120):
        """True if, in the same mmc-agent start, the admin plugin was loaded successfully before this failure:
        a successful load logs « Plugin admin loaded » twice in a row (import, then activate() OK), a failed one
        « Plugin admin loaded » then « Plugin admin not loaded ». Works at INFO level."""
        events = []
        for line in self.raw_logs.get("mmc-agent.log", []):
            ts = log_time(line)
            if ts is None or not (when - datetime.timedelta(seconds=seconds) <= ts <= when):
                continue
            if re.search(r"Plugin admin not loaded", line):
                events.append("E")
            elif re.search(r"Plugin admin loaded", line):
                events.append("L")
            elif "Importing available MMC plugins" in line:
                events = []          # new start: forget the previous one
        return "LL" in "".join(events) and events[-1:] == ["E"]

    def _context_before(self, source, when, seconds=10, n=15):
        """Lines of `source` (any level) logged up to `seconds` before `when`, secrets masked."""
        out = []
        for line in self.raw_logs.get(source, []):
            ts = log_time(line)
            if ts is not None and when - datetime.timedelta(seconds=seconds) <= ts <= when:
                out.append("   " + mask_secrets(" ".join(line.split()))[:200])
        return out[-n:] or ["   -"]

    def check_logs(self, hours=LOG_SINCE_HOURS, show_all=False):
        """Read every Medulla log (and GLPI's when local), keep the errors of the last `hours`,
        group them by signature and explain the known ones."""
        r = self.rep
        r.section(T("sec_logs", h=hours))
        since = datetime.datetime.now() - datetime.timedelta(hours=hours)
        known = {}            # key -> {"n", "last", "files", "example"}
        unknown = {}          # signature -> {...}: unexplained errors of the logs involved in the ITSM link
        other = {}            # signature -> {...}: errors of the other Medulla modules (deployment, updates...)
        read, scanned = [], 0
        for source, lines in self._log_sources(since):
            read.append(source)
            if source == "mmc-agent.log":
                self.raw_logs[source] = lines
            current, in_window, errors = None, False, 0
            entries = []
            for line in lines:
                ts = log_time(line)
                if ts is not None:
                    in_window = ts >= since
                    if not in_window:
                        current = None
                        continue
                    scanned += 1
                    current = [ts, line, []]
                    level = log_level(line)
                    if level not in ("DEBUG", "INFO", "NOTICE") and RX_DB_INIT_CAUSE.search(line):
                        self.db_init_causes.append((ts, source, line))
                    if level in ("DEBUG", "INFO", "NOTICE"):
                        continue                    # never an error, whatever its data contains
                    known_hit = any(re.search(rx, line) for _, rx, _ in LOG_PATTERNS)
                    if level in ("WARNING", "WARN") and not known_hit:
                        continue                    # warnings only count when they are a known GLPI problem
                    if level or known_hit or RX_LOG_ERROR.search(line):
                        entries.append(current)
                elif in_window and current is not None and len(current[2]) < 40:
                    current[2].append(line)     # continuation (traceback, multi-line message)
            itsm_source = self._is_itsm_log(source)
            for ts, line, more in entries:
                text = line + " " + " ".join(x.strip() for x in more)
                key = next((k for k, rx, _ in LOG_PATTERNS if re.search(rx, text)
                            and (k not in LOG_NEEDS_GLPI_CONTEXT or RX_GLPI_CONTEXT.search(text))
                            and (not k.startswith("forward_") or itsm_source)), None)
                if key is None and not (log_level(line) or RX_LOG_ERROR.search(line)):
                    continue
                if key is None and re.fullmatch(r".* - ERROR - b?['\"]?<.*", line):
                    continue                    # body of a rejected forward (old plugin): counted with its code
                errors += 1
                example = line
                if key is not None:
                    # the line that actually matched (it may be inside a traceback)
                    rx = next(x for k, x, _ in LOG_PATTERNS if k == key)
                    hit = next((x for x in [line] + more if re.search(rx, x)), line)
                    example = hit if hit is line else f"{line[:19]} {hit.strip()}"
                if key is None and more and "Traceback" in line:
                    # a traceback is identified by its exception (last non-indented line) and where it happened
                    last = next((x for x in reversed(more) if x.strip() and not x.startswith(" ")), line)
                    where = next((x.strip() for x in reversed(more) if x.strip().startswith("File ")), "")
                    sig = log_signature(last + " " + where)
                    example = f"{line[:19]} {last.strip()} ({where})" if where else f"{line[:19]} {last.strip()}"
                else:
                    sig = log_signature(line)
                # « Plugin X not loaded » of a plugin other than admin / glpi: not part of the GLPI link
                other_plugin = key is None and re.search(r"Plugin \w+ not loaded|Module \w+ raise an exception", line) \
                    and not re.search(r"Plugin (admin|glpi)\b|Module (admin|glpi)\b", line)
                bucket = known.setdefault(key, {}) if key else \
                    (unknown if itsm_source and not other_plugin else other).setdefault(sig, {})
                bucket["n"] = bucket.get("n", 0) + 1
                bucket["last"] = max(bucket.get("last", ts), ts)
                bucket.setdefault("files", set()).add(source)
                bucket["example"] = mask_secrets(" ".join(example.split()))[:220]
                if key == "mmc_plugin":
                    mm = re.search(r"Plugin (admin|glpi)", text)
                    bucket["module"] = mm.group(1) if mm else None
            if errors:
                r.info(T("log_file_errors", file=source, n=errors))
        if self.unreadable_logs:
            r.warn(T("log_unreadable_n", n=len(self.unreadable_logs),
                     list=", ".join(os.path.basename(x) for x in self.unreadable_logs)),
                   T("hint_run_as_root", cmd=root_cmd()) if os.geteuid() != 0 else None)
        if not read:
            r.info(T("log_none_read", dir=MMC_LOG_DIR, h=hours))
            return
        r.info(T("log_read", n=len(read), lines=scanned, h=hours))
        if not any(src.startswith("glpi:") for src in read):
            r.info(T("log_glpi_remote"))
        for key, _rx, severity in LOG_PATTERNS:
            b = known.get(key)
            if not b:
                continue
            msg = T("log_" + key, n=b["n"], last=b["last"].strftime("%Y-%m-%d %H:%M"),
                    files=", ".join(sorted(b["files"])))
            if severity == "info":
                r.info(msg)
                continue
            hint = [T("hint_log_" + key), T("log_example", line=b["example"])]
            if key == "mmc_plugin":
                started = service_started("mmc-agent")
                if started and b["last"] < started:
                    r.info(msg + " — " + T("log_before_start", start=started.strftime("%Y-%m-%d %H:%M:%S")))
                    continue
                if b.get("module") == "admin" and self._admin_loaded_before(b["last"]):
                    r.info(msg + " — " + T("log_admin_double_load"))
                    continue
                if started:
                    hint.insert(0, T("log_since_start", start=started.strftime("%Y-%m-%d %H:%M:%S")))
                # cause logged just before (up to 2 minutes), in the same log
                causes = [c for c in self.db_init_causes if "mmc-agent" in c[1]
                          and datetime.timedelta(0) < b["last"] - c[0] <= datetime.timedelta(minutes=2)
                          and cause_module(c[2]) in (None, b.get("module"))]
                hint.insert(1 if started else 0,
                            T("log_cause", line=mask_secrets(" ".join(causes[-1][2].split()))[:220]) if causes
                            else T("log_no_cause"))
                if not causes:
                    code = self.admin_code or {}
                    others = code.get("activators", []) + code.get("db_backend_users", [])
                    if code.get("returns_none") and code.get("plugin_tests_not") and b.get("module") == "admin" \
                            and self.admin_schema_ok and others:
                        hint.insert(2 if started else 1, T("log_admin_double_activation", list=", ".join(others[:4])))
                    elif b.get("module") == "admin" and self.admin_schema_ok:
                        hint.insert(2 if started else 1, T("log_admin_unexplained", level=mmc_agent_log_level()))
                    hint += [T("log_context")] + self._context_before("mmc-agent.log", b["last"])
                # schema out of date at that start, up to date now: the update was applied, a restart is enough
                if causes and re.search(r"lastest schema|database updated", causes[-1][2]) and self.admin_schema_ok:
                    hint.insert(2 if started else 1, T("log_schema_updated_restart"))
            # past events: warnings; the live checks above (API, forward, federation...) are authoritative
            r.warn(msg, hint)
        if unknown:
            top = sorted(unknown.items(), key=lambda kv: (-kv[1]["n"], kv[0]))
            shown = top if show_all else top[:LOG_TOP]
            r.warn(T("log_other_errors", n=sum(b["n"] for _, b in top), k=len(top)),
                   [f"{b['n']:>5}× {', '.join(sorted(b['files']))} — {b['example']}" for _, b in shown] +
                   ([T("log_more", k=len(top) - len(shown))] if len(top) > len(shown) else []))
        if other:
            # not part of this diagnosis: listed for information only (details with --all-errors)
            top = sorted(other.items(), key=lambda kv: (-kv[1]["n"], kv[0]))
            files = sorted({f for _, b in top for f in b["files"]})
            r.info(T("log_other_modules", n=sum(b["n"] for _, b in top), k=len(top), files=", ".join(files)))
            if show_all:
                for _, b in top:
                    print(f"      {dim('→')} {b['n']:>5}× {', '.join(sorted(b['files']))} — {b['example']}")
        if not known and not unknown:
            r.ok(T("log_clean_itsm", h=hours))

    def collect(self, hours=LOG_SINCE_HOURS):
        """Diagnostic archive for the support: logs (tails) and configuration files, secrets masked."""
        r = self.rep
        r.section(T("sec_collect"))
        ts = datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
        dest = os.path.join(os.path.expanduser("~"), f"medulla_itsm_diag-{ts}.tar.gz")
        since = datetime.datetime.now() - datetime.timedelta(hours=max(hours, 72))
        files = {}
        for source, lines in self._log_sources(since):
            files["logs/" + source.replace(":", "_").replace("/", "_")] = "\n".join(mask_secrets(x) for x in lines)
        conf_files = [GLPI_INI, GLPI_INI_LOCAL, REGAGENT_INI, REGAGENT_INI + ".local", CLIENT_INV_INI,
                      XMPPMASTER_INI, XMPPMASTER_INI + ".local", GEN_OPTIONS, MMC_AGENT_CONF, MMC_AGENT_CONF + ".local"]
        for sub in substitutes():
            conf_files += [sub["base"], sub["local"]]
        summary = []
        print_config_summary(config_summary_lines(), summary.append)
        files["script-version.txt"] = f"medulla_itsm {SCRIPT_VERSION}\n"
        files["effective-configuration.txt"] = re.sub(r"\x1b\[[0-9;]*m", "", "\n".join(summary)) + "\n"
        for path in conf_files:
            try:
                with open(path, encoding="utf-8", errors="replace") as fh:
                    content = fh.read()
            except OSError:
                continue
            # whole value hidden for any key that looks like a secret
            content = re.sub(r"--(aes-key|[\w-]*passw\w*)=\S+", r"--\1=********", content)
            content = re.sub(r"(?m)^(\s*[^#;\s][^=]*=\s*)(.*)$",
                             lambda m: m.group(1) + ("********" if SECRET_KEYS.search(m.group(1)) and m.group(2)
                                                     else m.group(2)), content)
            files["config" + path] = mask_secrets(content)
        old = os.umask(0o077)
        try:
            with tarfile.open(dest, "w:gz") as tar:
                for name, text in files.items():
                    data = text.encode("utf-8")
                    info = tarfile.TarInfo(f"medulla_itsm_diag-{ts}/{name}")
                    info.size, info.mtime, info.mode = len(data), int(time.time()), 0o600
                    tar.addfile(info, fileobj=io.BytesIO(data))
            r.ok(T("collect_ok", file=dest, n=len(files)))
            r.info(T("collect_note"))
        except OSError as e:
            r.fail(T("collect_ko", err=short(e)), fix="manual")
        finally:
            os.umask(old)

    # ── Configuration read on the Medulla server ──────────────────────────────
    def check_config(self):
        """Show every value read from the configuration and check what does not depend on GLPI."""
        r, p = self.rep, self.p
        r.section(T("sec_config"))
        r.info(T("cfg_intro"))
        print_config_summary(config_summary_lines())
        files = [GLPI_INI_LOCAL, REGAGENT_INI + ".local"] + [s["local"] for s in substitutes()]
        unreadable = [f for f in files if os.path.exists(f) and not os.access(f, os.R_OK)]
        if unreadable:
            r.warn(T("cfg_unreadable", n=len(unreadable), list=", ".join(os.path.basename(f) for f in unreadable)),
                   T("hint_run_as_root", cmd=root_cmd()))
        # several inventory substitutes on this server: they must forward the same way
        invs = inv_substitutes()
        if len(invs) > 1:
            ref = invs[0]
            for sub in invs[1:]:
                diffs = [k for k in ("enable_forward", "url_to_forward", "inventory_injection_mode", "inventory_plugin")
                         if inv_setting(sub, k).strip() != inv_setting(ref, k).strip()]
                if diffs:
                    r.warn(T("cfg_inv_differs", file=sub["local"], ref=ref["local"], keys=", ".join(diffs)),
                           T("hint_fix_mode"))
                else:
                    r.ok(T("cfg_inv_same", file=sub["local"], ref=os.path.basename(ref["local"])))
        elif not invs:
            r.warn(T("cfg_no_inv_substitute", dir=SUBST_DIR))
        # substitutes running on other servers read their own configuration there
        remote = remote_substitutes()
        if remote:
            r.warn(T("cfg_remote_substitutes", n=len(remote), list=", ".join(f"{j} ({t})" for j, t in remote)),
                   T("hint_cfg_remote_substitutes"))
        # injection mode of the inventory substitute
        r.info(T("cfg_injection_mode", mode=p.inv_mode))
        if p.inv_mode in ("module", "both") and p.readonly:
            r.fail(T("cfg_module_readonly", mode=p.inv_mode), T("hint_cfg_module_readonly"), fix="params")
        if p.inv_mode == "forward" and not p.inv_forward and not p.readonly:
            r.warn(T("cfg_no_injection"), T("hint_cfg_no_injection"))
        # TLS to the GLPI database: only mmc-agent supports it
        if p.db_ssl:
            r.warn(T("cfg_db_ssl"), T("hint_cfg_db_ssl"))
        # URLs written in glpi.ini must all point to the same GLPI
        cp = read_ini(GLPI_INI, GLPI_INI_LOCAL)
        uri = ini_get(cp, "main", "glpi_computer_uri", "")
        base = ini_get(cp, "authentication_glpi", "baseurl", "")
        for key, value in (("glpi_computer_uri", uri.split("/front/")[0]), ("baseurl", base),
                           ("glpi_base_url", api_root(p.api_url))):
            if value and p.url and not same_url(value, p.url):
                r.warn(T("cfg_url_differs", opt=key, value=value, url=p.url), T("hint_fix_mode"))
        for url in forward_urls(p.inv_forward_url) if p.inv_forward else []:
            if p.url and url_host_port(url) != url_host_port(p.url):
                r.warn(T("cfg_forward_other_host", url=url, web=p.url))
        # .generation_options vs the inventory agent
        disabled = generation_disables_inventory()
        if disabled and p.inv_forward:
            r.info(T("cfg_agent_inventory_disabled", file=GEN_OPTIONS))

    # ── 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))
        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"))
        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}
        # Every substitute loading the glpi plugin reads [glpidatabase]; a key it does not find falls back to
        # localhost / mmc / mmc, i.e. the LOCAL GLPI.
        for sub in glpi_substitutes(include_unused=True):
            diffs = [k for k, v in expected.items() if sub["glpidb"][k] != str(v)]
            defaults = [k for k in diffs if sub["glpidb_src"][k] == "default"]
            if not diffs:
                r.ok(T("conf_consistent", file=sub["local"]))
            elif sub["active"] is False and sub["enabled"] is False:
                r.info(T("conf_mismatch_inactive", file=sub["local"], keys=", ".join(diffs), svc=sub["service"]))
            else:
                r.fail(T("conf_mismatch", file=sub["local"], keys=", ".join(diffs)),
                       ([T("hint_conf_defaults", keys=", ".join(defaults))] if defaults else []) + [T("hint_fix_mode")])
        if p.inv_forward and p.inv_mode != "module":
            for sub in inv_substitutes():
                if inv_setting(sub, "enable_forward").strip().lower() not in ("true", "1", "yes"):
                    r.fail(T("conf_mismatch", file=sub["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 True:  # admin.saas_application is local: always checked
            saas, err = read_saas()
            if err:
                r.fail(T("saas_read_ko", err=err), fix="manual")
            else:
                rows, _ = read_saas_rows()
                misnamed = saas_misnamed(rows)
                for stored, expected in misnamed:
                    r.fail(T("saas_misnamed", stored=repr(stored), expected=expected), T("hint_fix_mode"))
                bad_names = {expected for _, expected in misnamed}
                for name, value in saas.items():
                    if name in SAAS_DESCRIPTIONS and value == "" and any(
                            n == name and isinstance(v, str) and v != v.strip() for n, v in rows):
                        r.warn(T("saas_value_spaces", name=name))
                empty = [name for name in SAAS_KEYS.values()
                         if name != SAAS_KEYS["crypt_key"] and name not in bad_names 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 "type_api" in bad_names:
                    pass                                    # already reported as mistyped
                elif 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("/"):
                    if api_session_ok(saas_url, p):
                        r.info(T("saas_url_differs_ok", saas=saas_url, ini=p.api_url))
                    else:
                        r.warn(T("saas_url_mismatch", saas=saas_url, ini=p.api_url), T("hint_fix_mode"))

    def check_admin_plugin(self):
        """mmc-agent plugin admin: it serves admin.saas_application (GLPI API settings) to the console.
        Same checks as its start (pulse2/database/admin activate + mmc/database db_check), with the effective
        configuration admin.ini then admin.ini.local."""
        r = self.rep
        r.section(T("sec_admin_plugin"))
        cp = read_ini(ADMIN_INI, ADMIN_INI + ".local")
        src = os.path.basename(ADMIN_INI) + (".local" if os.path.exists(ADMIN_INI + ".local") else "")
        if ini_get(cp, "main", "disable", "0").strip().lower() in ("1", "true", "yes"):
            r.warn(T("admin_disabled", file=src), T("hint_admin_disabled"))
            return
        db = {"host": ini_get(cp, "database", "dbhost", "localhost") or "localhost",
              "port": to_int(ini_get(cp, "database", "dbport", "3306"), 3306),
              "database": ini_get(cp, "database", "dbname", "admin") or "admin",
              "user": ini_get(cp, "database", "dbuser", "mmc") or "mmc",
              "password": ini_get(cp, "database", "dbpasswd", "")}
        r.info(T("admin_db_target", user=db["user"], host=db["host"], port=db["port"], db=db["database"], file=src))
        try:
            conn = db_connect(**db)
        except DBError as e:
            r.fail(T("admin_db_conn_ko", err=short(e)), T("hint_admin_conf", file=ADMIN_INI + ".local"))
            return
        try:
            tables = {t for (t,) in db_query(conn, "SHOW TABLES")}
            missing = [t for t in ADMIN_TABLES if t not in tables]
            blocking = [t for t in missing if t in ("version", "saas_application")]
            if blocking:
                r.fail(T("admin_tables_missing", list=", ".join(blocking)), T("hint_admin_schema"))
            if [t for t in missing if t not in blocking]:
                r.warn(T("admin_tables_optional", list=", ".join(t for t in missing if t not in blocking)),
                       T("hint_admin_schema"))
            if not missing:
                r.ok(T("admin_tables_ok", n=len(ADMIN_TABLES)))
            version = None
            if "version" in tables:
                rows = db_query(conn, "SELECT Number FROM version LIMIT 1")
                version = to_int(rows[0][0], None) if rows else None
            expected = None
            for d in ADMIN_SQL_DIRS:
                nums = [int(m.group(1)) for f in glob.glob(os.path.join(d, "schema-*.sql"))
                        for m in [re.search(r"schema-(\d+)\.sql$", f)] if m]
                if nums:
                    expected = max(nums)
                    break
            if version is None:
                r.fail(T("admin_version_none"), T("hint_admin_schema"))
            elif expected is None:
                r.info(T("admin_version_only", v=version))
            elif version == expected:
                r.ok(T("admin_version_ok", v=version))
                self.admin_schema_ok = True
            elif version < expected:
                r.warn(T("admin_version_old", v=version, exp=expected), T("hint_admin_schema"))
            else:
                r.fail(T("admin_version_newer", v=version, exp=expected), T("hint_admin_schema"))
        except DBError as e:
            r.fail(T("admin_db_conn_ko", err=short(e)), T("hint_admin_conf", file=ADMIN_INI + ".local"))
        finally:
            conn.close()
        self.admin_code = inspect_admin_activation()
        code = self.admin_code
        if code:
            r.info(T("admin_code_root", root=code["root"]))
            if code["returns_none"] and code["plugin_tests_not"]:
                r.info(T("admin_code_none"))
            if code["double_load"]:
                r.info(T("admin_code_double_load"))
            if code["activators"]:
                r.info(T("admin_code_activators", list=", ".join(code["activators"][:8])))
            if code["conditional"]:
                r.info(T("admin_code_conditional", list=", ".join(code["conditional"][:4]),
                         users=", ".join(code["db_backend_users"][:8]) or T("none")))

    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, Wrapper 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, wrapper = rows[0]
                    r.info(T("fed_wrapper", wrapper=wrapper))
                    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:
                if os.geteuid() != 0:
                    r.info(T("fedserver_unverified"))
                else:
                    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 sub in unused_glpi_substitutes():
            r.info(T("service_unused", svc=sub["service"]))
        for svc in glpi_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()
        self.simulate_forward()

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


# ─────────────────────────────────────────────────────────────────────────────
# SQL file (glpi-100.sql / glpi-110.sql)
# ─────────────────────────────────────────────────────────────────────────────
def apply_sql_file(p, major, rep):
    refuse_in_check_mode("apply an SQL file")
    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:
            tls = [f"--ssl-{k}={v}" for k, v in (p.db_ssl or {}).items() if v]
            res = subprocess.run(["mysql", "-h", p.db_host, "-P", str(p.db_port), "-u", p.db_user] + tls + [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, quiet=False):
    """Quick look at GLPI while prompting, to suggest the right URLs.
    Returns (major or None, core.url_base or "")."""
    try:
        conn = glpi_connect(p)
        try:
            cfg = dict(db_query(conn, "SELECT name, value FROM glpi_configs WHERE context='core' "
                                      "AND name IN ('version','url_base')"))
            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:
        if not quiet:
            print(f"    {yellow('[!]')} {T('probe_ko', err=short(e, 120))}")
        return None, ""
    version = cfg.get("version") or ""
    url_base = (cfg.get("url_base") or "").strip().rstrip("/")
    m = re.match(r"(\d+)\.", version)
    if not m:
        return None, url_base
    major = int(m.group(1))
    if not quiet:
        print(f"    {green('[✓]')} {T('glpi_version_ok', v=version)}")
        if url_base:
            print(f"    {cyan('[=]')} {T('glpi_url_base_found', url=url_base)}")
        if major in SQL_FILES and not set(REQUIRED_VIEWS) <= views:
            print(f"    {yellow('[!]')} {T('hint_apply_sql', url=SQL_FILES[major])}")
    return major, url_base


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, url_base = probe_glpi_version(p)
    if url_base and not same_url(url_base, p.url):
        # The URL GLPI declares for itself is the reference: glpi_computer_uri, baseurl and the forward URL
        print(f"    {yellow('[!]')} {T('url_base_mismatch', glpi=url_base, medulla=p.url)}")
        if ask_yn(T("use_glpi_url_base", url=url_base), True):
            p.url = url_base
    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("/")
    # API (admin.saas_application on the local Medulla DB): asked even when the GLPI DB is read-only
    # read-only: the installer writes no API login (no purge of machines); the user token is enough
    p.api_user = ask(T("lbl_api_user"), p.api_user, required=not p.readonly)
    p.api_pass = ask(T("lbl_api_pass"), p.api_pass, secret=True, required=not p.readonly)
    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')}")
    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)
    # Read-only does not prevent forwarding: GLPI itself stores the forwarded inventory (the Medulla
    # installer keeps enable_forward = True in read-only mode)
    p.inv_forward = ask_yn(T("lbl_inv_forward"), p.inv_forward)
    if p.inv_forward:
        print(f"    {cyan('[=]')} {T('cfg_injection_mode', mode=p.inv_mode)}")
    if p.inv_forward and p.inv_mode != "module":
        # Offered by default: the URL built from GLPI's own core.url_base, NOT the current value
        # (a wrong current value would otherwise be kept with a single Enter).
        expected = forward_url_for(url_base or p.url)
        current = (p.inv_forward_url or "").strip()
        if current and not any(same_url(u, expected) for u in forward_urls(current)):
            print(f"    {yellow('[!]')} {T('forward_current_differs', current=current, expected=expected)}")
        several = len(forward_urls(current)) > 1 and any(same_url(u, expected) for u in forward_urls(current))
        default = current if (current and (several or getattr(p, "forward_url_from_args", False))) else expected
        p.inv_forward_url = ask(T("lbl_inv_url"), default, validator=v_url)
    if p.inv_forward:
        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.forward_url_from_args = bool(args.inv_forward_url)
    p.verify_ssl = not args.insecure
    if interactive:
        p = prompt_params(p)
    else:
        if p.inv_forward and not p.inv_forward_url and p.db_host and not v_dbhost(p.db_host):
            _, url_base = probe_glpi_version(p, quiet=True)
            p.inv_forward_url = forward_url_for(url_base or p.url)
        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"),
             T("plan_saas")]
    inv_files = [s["local"] for s in inv_substitutes()] or [SUBS_INV_INI + ".local"]
    if p.inv_forward:
        items += [T("plan_update_file", file=f) for f in inv_files] + [T("plan_update_file", file=CLIENT_INV_INI)]
    else:
        items += [T("plan_forward_off", file=f) for f in inv_files if os.path.exists(f)]
    for sub in glpi_substitutes(include_unused=True):
        if sub["kind"] != "inv" or not p.inv_forward:
            items.append(T("plan_update_glpidb", file=sub["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_ask", list=", ".join(glpi_services())), T("plan_reconf_ask")]
    if p.inv_agent_disabled and generation_disables_inventory() is not True:
        items.append(T("plan_regen"))
    for item in items:
        print(f"    • {item}")


CHECK_ONLY = False      # True while check mode runs: every writing code path refuses to start


def refuse_in_check_mode(what):
    if CHECK_ONLY:
        raise RuntimeError(f"check mode is read-only: refused to {what}")


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

    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 _server_sql(self, wrapper):
        p = self.p
        return (f"CREATE OR REPLACE SERVER {FEDERATED_SERVER} FOREIGN DATA WRAPPER '{wrapper}' 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)})")

    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)."""
        r = self.rep
        try:
            conn, who = medulla_admin_connect()
        except (DBError, PermissionError) as e:
            r.fail(T("federated_apply_ko", err=short(e)), list(ADMIN_ERRORS) + [T("hint_fed_priv")])
            return False
        if who != medulla_db_settings()["user"]:
            r.info(T("fed_using_root"))
        try:
            cur = conn.cursor()
            cur.execute(self._server_sql("mariadb"))
            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)))
            # Same fallback as the Medulla installer (Ansible mmc role): when the 'mariadb' wrapper cannot
            # read GLPI, the server is recreated with the 'mysql' wrapper.
            try:
                cur.execute("SELECT 1 FROM `xmppmaster`.`local_glpi_configs` LIMIT 1")
                cur.fetchall()
            except DBError as e:
                r.info(T("fed_wrapper_retry", err=short(e, 140)))
                cur.execute(self._server_sql("mysql"))
                try:
                    cur.execute("FLUSH TABLES " + ", ".join(f"`xmppmaster`.`{n}`" for n in FEDERATED_TABLES))
                except DBError:
                    pass
                try:
                    cur.execute("SELECT 1 FROM `xmppmaster`.`local_glpi_configs` LIMIT 1")
                    cur.fetchall()
                    r.ok(T("fed_wrapper_mysql_ok"))
                except DBError as e2:
                    r.fail(T("federated_apply_ko", err=short(e2)), T("hint_fix_mode"))
            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")
            rows = [(str(n or ""), v) for n, v in cur.fetchall()]
            for stored, expected in saas_misnamed(rows):
                # exact (binary) match on the stored name, so only that row is renamed
                cur.execute("UPDATE saas_application SET setting_name=%s "
                            "WHERE CAST(setting_name AS BINARY) = CAST(%s AS BINARY)", (expected, stored))
                r.ok(T("saas_renamed", stored=repr(stored), expected=expected))
            cur.execute("SELECT setting_name, setting_value FROM saas_application")
            current = {str(name): (value or "").strip() 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}
            # an API URL already stored and working is kept: the fix mode only changes what does not work
            stored_url = current.get(SAAS_KEYS["api_url"], "")
            if stored_url and not same_url(stored_url, p.api_url) and api_session_ok(stored_url, p):
                values.pop(SAAS_KEYS["api_url"])
                r.info(T("saas_url_kept", url=stored_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 key_name not in current:
                values[key_name] = ""               # row created empty, as the Medulla installer does
            for name, value in values.items():
                if name in current:
                    cur.execute("UPDATE saas_application SET setting_value=%s "
                                "WHERE CAST(setting_name AS BINARY) = CAST(%s AS BINARY)", (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 want_restart(self):
        """Restart only with an explicit yes (interactive, default No) or --restart (non-interactive)."""
        if self.args.no_restart:
            return False
        if self.args.restart:
            return True
        if self.interactive:
            print()
            print(dim("  " + T("restart_why", list=", ".join(glpi_services()))))
            return ask_yn(T("restart_confirm"), False)
        return False

    def restart(self):
        """Restart the services that read the modified files (not every Medulla service).
        Returns True if they were restarted."""
        r = self.rep
        r.section(T("sec_restart"))
        if not self.want_restart():
            r.warn(T("restart_skipped"), [f"systemctl restart {' '.join(glpi_services())}"])
            return False
        if not shutil.which("systemctl"):
            r.warn(T("tool_missing", tool="systemctl"))
            return
        for svc in glpi_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")
        return True

    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:
                wanted = False
            elif self.args.reconf:
                wanted = True
            elif self.interactive:
                print()
                print(dim("  " + T("reconf_why")))
                wanted = ask_yn(T("reconf_confirm", n=count), False)
            else:
                wanted = False
            if not wanted:
                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,
                       "glpi_username": p.api_user or None, "glpi_password": p.api_pass or None}
        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"}})
        self.saas()
        # every inventory substitute of this server (inv, inv2...) gets the same forward settings
        inv_files = [s["local"] for s in inv_substitutes()] or [SUBS_INV_INI + ".local"]
        if p.inv_forward:
            for path in inv_files:
                self.write_ini(path, {
                    "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:
            for path in inv_files:
                self.write_ini(path, {"glpi": {"enable_forward": "False"}}, create=False)
        # [glpidatabase] of every substitute loading the glpi plugin (registration, inventory, master,
        # diskmastering...): a missing key would make it use the local GLPI (localhost / mmc / mmc).
        for sub in glpi_substitutes(include_unused=True):
            if sub["kind"] == "inv" and p.inv_forward:
                continue                            # already written above
            self.write_ini(sub["local"], {"glpidatabase": dbsec})
        self.write_ini(REGAGENT_INI + ".local",
                       {"parameters": {"check_uuidinventory": "True" if p.readonly else None}},
                       create=p.readonly)
        self.restarted = self.restart()
        self.reconfigure_agents()
        # regenerate only when it changes: .generation_options already holding --disable-inventory means done
        if p.inv_agent_disabled and generation_disables_inventory() is not True:
            self.regenerate_agent()


# ─────────────────────────────────────────────────────────────────────────────
# Modes
# ─────────────────────────────────────────────────────────────────────────────
def mode_check(args, interactive):
    global CHECK_ONLY
    CHECK_ONLY = True
    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
    ck.check_config()
    if err:
        rep.warn(T("saas_read_ko", err=err))
    validate_params(p, rep, intro=T("params_from_config"))
    ck.run_remote()
    ck.run_local()
    ck.check_forward_log()
    ck.check_logs(args.since, args.all_errors)
    if args.collect:
        ck.collect(args.since)
    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):
    global CHECK_ONLY
    CHECK_ONLY = False          # fix mode may be started from check mode (offer_fix / offer_connect)
    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.
        # Kept: what describes the Medulla side, and a substitute already pointing to an external GLPI.
        full, _ = load_current_params()
        current = Params(inv_mode=full.inv_mode, inv_agent=full.inv_agent, inv_plugin=full.inv_plugin,
                         inv_agent_disabled=full.inv_agent_disabled, inv_forward=full.inv_forward)
        if full.db_host and full.db_host.lower() != "localhost":
            for k in ("db_host", "db_port", "db_name", "db_user", "db_pass"):
                setattr(current, k, getattr(full, k))
        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 = Applier(p, applied, interactive, args)
    applier.run()

    reset_substitutes_cache()      # files written / services restarted: read them again
    if applier.restarted:
        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=f"medulla_itsm {SCRIPT_VERSION} — Check / configure the connection between Medulla and an "
                                             "external GLPI (ITSM).")
    ap.add_argument("--version", action="version", version=f"medulla_itsm {SCRIPT_VERSION}")
    ap.add_argument("-v", "--verbose", action="store_true",
                    help="debug output: every file read, SQL query, HTTP call and command (secrets masked), "
                         "every distinct log error, Python traceback on an unexpected error")
    ap.add_argument("--lang", choices=LANGS, help="Interface language (default: from $LANG)")
    ap.add_argument("--mode", choices=("check", "fix"), help="check = read-only diagnostics (nothing is modified), "
                                                             "fix = configure")
    ap.add_argument("--non-interactive", action="store_true",
                    help="Never prompt (for automation). fix: nothing is restarted / reconfigured unless "
                         "--restart / --reconf")
    ap.add_argument("--insecure", action="store_true", help="Do not verify TLS certificates (the inventory "
                                                             "forward is always tested with verification)")
    ap.add_argument("--since", type=int, default=LOG_SINCE_HOURS, metavar="HOURS",
                    help=f"check: analyse the errors of the last HOURS in {MMC_LOG_DIR}/*.log, the services' journal "
                         f"and the GLPI logs if GLPI is local (default {LOG_SINCE_HOURS})")
    ap.add_argument("--all-errors", action="store_true", help="check: list every distinct error found in the logs")
    ap.add_argument("--collect", action="store_true",
                    help="check: also build ~/medulla_itsm_diag-<date>.tar.gz (logs + configuration, secrets masked) "
                         "to send to the support")
    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("--restart", action="store_true",
                    help="fix: restart mmc-agent and the substitutes reading the GLPI database without asking (needed for the new "
                         "configuration to be used; asked interactively, default No)")
    ap.add_argument("--no-restart", action="store_true", help="fix: never restart the services")
    ap.add_argument("--reconf", action="store_true",
                    help="fix: mark every Medulla agent for reconfiguration (need_reconf=1) without asking "
                         "(asked interactively, default No)")
    ap.add_argument("--no-reconf", action="store_true", help="fix: never 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, VERBOSE
    args = build_parser().parse_args()
    VERBOSE = args.verbose
    if VERBOSE:
        install_http_trace()
        args.all_errors = True
    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')}") + dim(f"  (medulla_itsm {SCRIPT_VERSION})"))
        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
    except Exception as e:          # unexpected: one line, full traceback with --verbose
        print()
        print(red(T("unexpected_error", err=short(e, 300))))
        if VERBOSE:
            import traceback
            traceback.print_exc()
        else:
            print(T("hint_verbose"))
        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 (read-only: nothing is modified)",
                   "Mode vérification — diagnostiquer la configuration actuelle (lecture seule : rien n'est modifié)",
                   "Modo verificación — diagnosticar la configuración actual (solo lectura: no se modifica nada)",
                   "Prüfmodus — aktuelle Konfiguration diagnostizieren (nur lesend: nichts wird geändert)"),
    "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."),
    "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}"),
    "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 lacks {list} to apply the SQL file of Medulla views: a GLPI DB administrator must apply it",
                              "Il manque {list} à cet utilisateur pour appliquer le fichier SQL des vues Medulla : un administrateur de la base GLPI devra l'appliquer",
                              "A este usuario le falta {list} para aplicar el archivo SQL de las vistas de Medulla: deberá aplicarlo un administrador de la BD de GLPI",
                              "Diesem Benutzer fehlt {list}, um die SQL-Datei der Medulla-Views anzuwenden: ein GLPI-DB-Administrator muss sie 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_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}"),

    # Inventory forward URL / web URL (blocking checks)
    "sec_forward_log": ("Inventory forwarding: latest results (substitute log)",
                        "Remontée d'inventaire : derniers résultats (journal du substitut)",
                        "Reenvío de inventario: últimos resultados (registro del sustituto)",
                        "Inventarweiterleitung: letzte Ergebnisse (Log des Substituts)"),
    "hint_url_not_glpi": ("No GLPI at this address: check the path (GLPI at the site root or under /glpi/?)",
                          "Pas de GLPI à cette adresse : vérifiez le chemin (GLPI à la racine du site ou sous /glpi/ ?)",
                          "No hay GLPI en esta dirección: revise la ruta (¿GLPI en la raíz del sitio o bajo /glpi/?)",
                          "Kein GLPI unter dieser Adresse: Pfad prüfen (GLPI im Wurzelverzeichnis oder unter /glpi/?)"),
    "hint_glpi_url_base": ("URL declared in GLPI (core.url_base): {url}", "URL déclarée dans GLPI (core.url_base) : {url}",
                           "URL declarada en GLPI (core.url_base): {url}", "In GLPI hinterlegte URL (core.url_base): {url}"),
    "hint_url_base_fix": ("Fix mode offers to use the URL declared in GLPI: {url}",
                          "Le mode correction propose d'utiliser l'URL déclarée dans GLPI : {url}",
                          "El modo corrección propone usar la URL declarada en GLPI: {url}",
                          "Der Korrekturmodus schlägt die in GLPI hinterlegte URL vor: {url}"),
    "hint_url_base_glpi": ("If GLPI's own value is wrong: GLPI > Setup > General > General setup > URL of the application",
                           "Si c'est la valeur de GLPI qui est fausse : GLPI > Configuration > Générale > Configuration générale > URL de l'application",
                           "Si el valor de GLPI es incorrecto: GLPI > Configuración > General > Configuración general > URL de la aplicación",
                           "Falls der GLPI-Wert falsch ist: GLPI > Einrichten > Allgemein > Allgemeine Einrichtung > URL der Anwendung"),
    "glpi_url_base_found": ("URL declared in GLPI (core.url_base): {url}", "URL déclarée dans GLPI (core.url_base) : {url}",
                            "URL declarada en GLPI (core.url_base): {url}", "In GLPI hinterlegte URL (core.url_base): {url}"),
    "use_glpi_url_base": ("Use the URL declared in GLPI ({url})?", "Utiliser l'URL déclarée dans GLPI ({url}) ?",
                          "¿Usar la URL declarada en GLPI ({url})?", "Die in GLPI hinterlegte URL ({url}) verwenden?"),
    "forward_current_differs": ("Current forward URL {current} differs from the one built from GLPI ({expected}): the latter is offered",
                                "L'URL de remontée actuelle {current} diffère de celle construite depuis GLPI ({expected}) : c'est cette dernière qui est proposée",
                                "La URL de reenvío actual {current} difiere de la construida desde GLPI ({expected}): se propone esta última",
                                "Die aktuelle Weiterleitungs-URL {current} weicht von der aus GLPI abgeleiteten ab ({expected}): letztere wird vorgeschlagen"),
    "forward_post_ok": ("{url}: GLPI inventory endpoint found (empty POST → HTTP {code})",
                        "{url} : point d'entrée d'inventaire GLPI trouvé (POST vide → HTTP {code})",
                        "{url}: punto de entrada de inventario de GLPI encontrado (POST vacío → HTTP {code})",
                        "{url}: GLPI-Inventar-Endpunkt gefunden (leerer POST → HTTP {code})"),
    "forward_post_ko": ("{url}: empty POST → HTTP {code}: GLPI will reject every forwarded inventory",
                        "{url} : POST vide → HTTP {code} : GLPI rejettera tous les inventaires remontés",
                        "{url}: POST vacío → HTTP {code}: GLPI rechazará todos los inventarios reenviados",
                        "{url}: leerer POST → HTTP {code}: GLPI wird jedes weitergeleitete Inventar ablehnen"),
    "hint_forward_code": ("Expected: HTTP 400 (GLPI 10/11 answers 400 to an empty POST on front/inventory.php)",
                          "Attendu : HTTP 400 (GLPI 10/11 répond 400 à un POST vide sur front/inventory.php)",
                          "Esperado: HTTP 400 (GLPI 10/11 responde 400 a un POST vacío en front/inventory.php)",
                          "Erwartet: HTTP 400 (GLPI 10/11 antwortet mit 400 auf einen leeren POST an front/inventory.php)"),
    "hint_forward_probable": ("Probable URL (from core.url_base): {url}", "URL probable (d'après core.url_base) : {url}",
                              "URL probable (según core.url_base): {url}", "Wahrscheinliche URL (laut core.url_base): {url}"),
    "hint_forward_probable_ok": ("Probable URL, tested: {url} (empty POST → HTTP {code})",
                                 "URL probable, testée : {url} (POST vide → HTTP {code})",
                                 "URL probable, probada: {url} (POST vacío → HTTP {code})",
                                 "Wahrscheinliche URL, getestet: {url} (leerer POST → HTTP {code})"),
    "forward_url_differs": ("Forward URL {url} differs from the one built from GLPI ({expected})",
                            "L'URL de remontée {url} diffère de celle construite depuis GLPI ({expected})",
                            "La URL de reenvío {url} difiere de la construida desde GLPI ({expected})",
                            "Die Weiterleitungs-URL {url} weicht von der aus GLPI abgeleiteten ab ({expected})"),
    "forward_redirect": ("{url} redirects (HTTP {codes} → {to}): the POST becomes a GET and the inventory is lost",
                         "{url} redirige (HTTP {codes} → {to}) : le POST devient un GET et l'inventaire est perdu",
                         "{url} redirige (HTTP {codes} → {to}): el POST se convierte en GET y el inventario se pierde",
                         "{url} leitet um (HTTP {codes} → {to}): aus dem POST wird ein GET, das Inventar geht verloren"),
    "hint_forward_redirect": ("Use the final URL directly: {url}", "Utilisez directement l'URL finale : {url}",
                              "Use directamente la URL final: {url}", "Direkt die End-URL verwenden: {url}"),
    "forward_tls_ko": ("{url}: TLS certificate rejected ({err}) — the inventory substitute verifies it: every forward will fail",
                       "{url} : certificat TLS refusé ({err}) — le substitut d'inventaire le vérifie : toutes les remontées échoueront",
                       "{url}: certificado TLS rechazado ({err}) — el sustituto de inventario lo verifica: todos los reenvíos fallarán",
                       "{url}: TLS-Zertifikat abgelehnt ({err}) — der Inventar-Substitut prüft es: jede Weiterleitung schlägt fehl"),
    "hint_forward_tls": ("--insecure does not apply to the substitute: the CA must be trusted by the Medulla server",
                         "--insecure ne s'applique pas au substitut : l'AC doit être reconnue par le serveur Medulla",
                         "--insecure no se aplica al sustituto: la CA debe ser reconocida por el servidor Medulla",
                         "--insecure gilt nicht für den Substitut: die CA muss dem Medulla-Server bekannt sein"),
    "inv_log_unreadable": ("{file} unreadable ({err}): latest forwards not checked",
                           "{file} illisible ({err}) : derniers transferts non vérifiés",
                           "{file} no legible ({err}): últimos reenvíos no verificados",
                           "{file} nicht lesbar ({err}): letzte Weiterleitungen nicht geprüft"),
    "inv_log_none": ("No inventory received recently in {file}", "Aucun inventaire reçu récemment dans {file}",
                     "Ningún inventario recibido recientemente en {file}", "Keine kürzlich empfangenen Inventare in {file}"),
    "inv_log_ok": ("Latest forwarded inventories accepted by GLPI: {total} of {total} (last: {date})",
                   "Dernières remontées d'inventaire acceptées par GLPI : {total} sur {total} (dernière : {date})",
                   "Últimos reenvíos de inventario aceptados por GLPI: {total} de {total} (último: {date})",
                   "Letzte Inventarweiterleitungen von GLPI angenommen: {total} von {total} (zuletzt: {date})"),
    "inv_log_last_ko": ("Latest inventory forward rejected ({date}: {err}) — {n}/{total} recent forwards failed ({codes})",
                        "Dernière remontée d'inventaire rejetée ({date} : {err}) — {n}/{total} remontées récentes en échec ({codes})",
                        "Último reenvío de inventario rechazado ({date}: {err}) — {n}/{total} reenvíos recientes fallidos ({codes})",
                        "Letzte Inventarweiterleitung abgelehnt ({date}: {err}) — {n}/{total} kürzliche Weiterleitungen fehlgeschlagen ({codes})"),
    "inv_log_some_ko": ("{n}/{total} recent inventory forwards failed ({codes}); the latest one ({date}) was accepted",
                        "{n}/{total} remontées d'inventaire récentes en échec ({codes}) ; la dernière ({date}) a été acceptée",
                        "{n}/{total} reenvíos de inventario recientes fallidos ({codes}); el último ({date}) fue aceptado",
                        "{n}/{total} kürzliche Inventarweiterleitungen fehlgeschlagen ({codes}); die letzte ({date}) wurde angenommen"),
    "hint_inv_log": ("Details: grep -E 'ERROR - [0-9]{{3}}$|Inventory forward' {file} | tail",
                     "Détail : grep -E 'ERROR - [0-9]{{3}}$|Inventory forward' {file} | tail",
                     "Detalle: grep -E 'ERROR - [0-9]{{3}}$|Inventory forward' {file} | tail",
                     "Details: grep -E 'ERROR - [0-9]{{3}}$|Inventory forward' {file} | tail"),
    "hint_inv_log_after_fix": ("After a fix, this check stays red until a new inventory has been received",
                               "Après une correction, ce contrôle reste en échec jusqu'à la réception d'un nouvel inventaire",
                               "Tras una corrección, esta verificación sigue fallando hasta recibir un nuevo inventario",
                               "Nach einer Korrektur bleibt diese Prüfung rot, bis ein neues Inventar eingegangen ist"),

    # GLPI version / inventory authentication
    "fact_plugin": ("Plugin", "Plugin", "Plugin", "Plugin"),
    "glpi_version_unreachable": ("GLPI version: database unreachable", "version GLPI : base injoignable",
                                 "versión de GLPI: BD inaccesible", "GLPI-Version: Datenbank nicht erreichbar"),
    "inventory_auth_ok": ("GLPI inventory: no agent authentication required", "Inventaire GLPI : aucune authentification d'agent exigée",
                          "Inventario de GLPI: no se exige autenticación de agente", "GLPI-Inventar: keine Agenten-Authentifizierung verlangt"),
    "inventory_auth_ko": ("GLPI inventory requires agent authentication ({mode}): the inventory substitute sends none, every forward gets HTTP 401",
                          "L'inventaire GLPI exige une authentification d'agent ({mode}) : le substitut d'inventaire n'en envoie pas, chaque remontée reçoit HTTP 401",
                          "El inventario de GLPI exige autenticación de agente ({mode}): el sustituto de inventario no la envía, cada reenvío recibe HTTP 401",
                          "Das GLPI-Inventar verlangt Agenten-Authentifizierung ({mode}): der Inventar-Substitut sendet keine, jede Weiterleitung erhält HTTP 401"),
    "hint_inventory_auth": ("GLPI: Administration > Inventory > Authorization header: None (or authorise the Medulla server otherwise)",
                            "GLPI : Administration > Inventaire > En-tête d'autorisation : Aucune (ou autoriser autrement le serveur Medulla)",
                            "GLPI: Administración > Inventario > Cabecera de autorización: Ninguna (o autorizar de otro modo al servidor Medulla)",
                            "GLPI: Verwaltung > Inventar > Autorisierungs-Header: Keiner (oder den Medulla-Server anders zulassen)"),

    # Simulation
    "sec_simulate": ("Simulated inventory forward (agent PROLOG)", "Simulation d'une remontée d'inventaire (PROLOG d'agent)",
                     "Simulación de un reenvío de inventario (PROLOG de agente)", "Simulierte Inventarweiterleitung (Agenten-PROLOG)"),
    "simu_what": ("Sent like the substitute does: gzip, User-Agent {ua}, DEVICEID {deviceid} (a PROLOG creates no computer in GLPI)",
                  "Envoi identique à celui du substitut : gzip, User-Agent {ua}, DEVICEID {deviceid} (un PROLOG ne crée aucune machine dans GLPI)",
                  "Envío idéntico al del sustituto: gzip, User-Agent {ua}, DEVICEID {deviceid} (un PROLOG no crea ningún equipo en GLPI)",
                  "Gesendet wie vom Substitut: gzip, User-Agent {ua}, DEVICEID {deviceid} (ein PROLOG legt in GLPI keinen Computer an)"),
    "simu_ok": ("{url}: GLPI accepted the agent request (PROLOG_FREQ = {freq} h) — forwarded inventories will be received",
                "{url} : GLPI a accepté la requête d'agent (PROLOG_FREQ = {freq} h) — les inventaires remontés seront reçus",
                "{url}: GLPI aceptó la petición de agente (PROLOG_FREQ = {freq} h) — los inventarios reenviados se recibirán",
                "{url}: GLPI hat die Agentenanfrage angenommen (PROLOG_FREQ = {freq} h) — weitergeleitete Inventare werden empfangen"),
    "simu_ko": ("{url}: GLPI refused the agent request (HTTP {code}): {err}",
                "{url} : GLPI a refusé la requête d'agent (HTTP {code}) : {err}",
                "{url}: GLPI rechazó la petición de agente (HTTP {code}): {err}",
                "{url}: GLPI hat die Agentenanfrage abgelehnt (HTTP {code}): {err}"),
    "hint_glpi_server_logs": ("See the GLPI server logs: files/_log/php-errors.log and sql-errors.log",
                              "Voir les journaux du serveur GLPI : files/_log/php-errors.log et sql-errors.log",
                              "Vea los registros del servidor GLPI: files/_log/php-errors.log y sql-errors.log",
                              "Siehe die Logs des GLPI-Servers: files/_log/php-errors.log und sql-errors.log"),

    # Logs
    "sec_logs": ("Server logs: errors of the last {h} h", "Journaux du serveur : erreurs des dernières {h} h",
                 "Registros del servidor: errores de las últimas {h} h", "Server-Logs: Fehler der letzten {h} h"),
    "log_file_errors": ("{file}: {n} error(s)", "{file} : {n} erreur(s)", "{file}: {n} error(es)", "{file}: {n} Fehler"),
    "log_none_read": ("No log written in {dir} during the last {h} h", "Aucun journal écrit dans {dir} pendant les dernières {h} h",
                      "Ningún registro escrito en {dir} en las últimas {h} h", "Kein Log in {dir} in den letzten {h} h geschrieben"),
    "log_read": ("{n} log(s) read, {lines} entries in the last {h} h", "{n} journal(aux) lu(s), {lines} entrées sur les dernières {h} h",
                 "{n} registro(s) leído(s), {lines} entradas en las últimas {h} h", "{n} Log(s) gelesen, {lines} Einträge in den letzten {h} h"),
    "log_glpi_remote": ("GLPI logs are on the GLPI server (files/_log/*.log): not read from here",
                        "Les journaux de GLPI sont sur le serveur GLPI (files/_log/*.log) : non lus d'ici",
                        "Los registros de GLPI están en el servidor GLPI (files/_log/*.log): no se leen desde aquí",
                        "Die GLPI-Logs liegen auf dem GLPI-Server (files/_log/*.log): von hier nicht gelesen"),
    "log_example": ("Last occurrence: {line}", "Dernière occurrence : {line}", "Última aparición: {line}", "Letztes Auftreten: {line}"),
    "log_other_errors": ("{n} other error(s) in the logs ({k} distinct):", "{n} autre(s) erreur(s) dans les journaux ({k} distincte(s)) :",
                         "{n} otro(s) error(es) en los registros ({k} distinto(s)):", "{n} weitere Fehler in den Logs ({k} verschiedene):"),
    "log_more": ("… {k} more (--all-errors to list them all)", "… {k} de plus (--all-errors pour tout afficher)",
                 "… {k} más (--all-errors para verlos todos)", "… {k} weitere (--all-errors zeigt alle)"),
    "log_forward_404": ("Logs: {n} inventory forward(s) rejected with HTTP 404 (last: {last}, {files})",
                        "Journaux : {n} remontée(s) d'inventaire rejetée(s) en HTTP 404 (dernière : {last}, {files})",
                        "Registros: {n} reenvío(s) de inventario rechazado(s) con HTTP 404 (último: {last}, {files})",
                        "Logs: {n} Inventarweiterleitung(en) mit HTTP 404 abgelehnt (zuletzt: {last}, {files})"),
    "hint_log_forward_404": ("Wrong url_to_forward (GLPI path): see the « Inventory forwarding » section above",
                             "url_to_forward erronée (chemin GLPI) : voir la section « Remontée d'inventaire » plus haut",
                             "url_to_forward incorrecta (ruta de GLPI): vea la sección « Reenvío de inventario » más arriba",
                             "Falsche url_to_forward (GLPI-Pfad): siehe Abschnitt „Inventarweiterleitung“ oben"),
    "log_forward_401": ("Logs: {n} inventory forward(s) rejected with HTTP 401 (last: {last}, {files})",
                        "Journaux : {n} remontée(s) d'inventaire rejetée(s) en HTTP 401 (dernière : {last}, {files})",
                        "Registros: {n} reenvío(s) de inventario rechazado(s) con HTTP 401 (último: {last}, {files})",
                        "Logs: {n} Inventarweiterleitung(en) mit HTTP 401 abgelehnt (zuletzt: {last}, {files})"),
    "hint_log_forward_401": ("GLPI requires agent authentication for the inventory: GLPI > Administration > Inventory > Authorization header",
                             "GLPI exige une authentification d'agent pour l'inventaire : GLPI > Administration > Inventaire > En-tête d'autorisation",
                             "GLPI exige autenticación de agente para el inventario: GLPI > Administración > Inventario > Cabecera de autorización",
                             "GLPI verlangt Agenten-Authentifizierung für das Inventar: GLPI > Verwaltung > Inventar > Autorisierungs-Header"),
    "log_forward_403": ("Logs: {n} inventory forward(s) refused (HTTP 403 / inventory disabled) (last: {last}, {files})",
                        "Journaux : {n} remontée(s) d'inventaire refusée(s) (HTTP 403 / inventaire désactivé) (dernière : {last}, {files})",
                        "Registros: {n} reenvío(s) de inventario denegado(s) (HTTP 403 / inventario desactivado) (último: {last}, {files})",
                        "Logs: {n} Inventarweiterleitung(en) verweigert (HTTP 403 / Inventar deaktiviert) (zuletzt: {last}, {files})"),
    "hint_log_forward_403": ("GLPI: Administration > Inventory > Enable inventory", "GLPI : Administration > Inventaire > Activer l'inventaire",
                             "GLPI: Administración > Inventario > Activar inventario", "GLPI: Verwaltung > Inventar > Inventar aktivieren"),
    "log_forward_5xx": ("Logs: {n} inventory forward(s) failed on the GLPI side (HTTP 5xx) (last: {last}, {files})",
                        "Journaux : {n} remontée(s) d'inventaire en erreur côté GLPI (HTTP 5xx) (dernière : {last}, {files})",
                        "Registros: {n} reenvío(s) de inventario con error en GLPI (HTTP 5xx) (último: {last}, {files})",
                        "Logs: {n} Inventarweiterleitung(en) mit Fehler auf GLPI-Seite (HTTP 5xx) (zuletzt: {last}, {files})"),
    "hint_log_forward_5xx": ("GLPI crashed while processing the inventory: GLPI server logs files/_log/php-errors.log, sql-errors.log",
                             "GLPI a planté en traitant l'inventaire : journaux du serveur GLPI files/_log/php-errors.log, sql-errors.log",
                             "GLPI falló al procesar el inventario: registros del servidor GLPI files/_log/php-errors.log, sql-errors.log",
                             "GLPI ist bei der Inventarverarbeitung abgestürzt: GLPI-Logs files/_log/php-errors.log, sql-errors.log"),
    "log_forward_net": ("Logs: {n} inventory forward(s) did not reach GLPI (network / DNS / timeout) (last: {last}, {files})",
                        "Journaux : {n} remontée(s) d'inventaire n'ont pas atteint GLPI (réseau / DNS / délai) (dernière : {last}, {files})",
                        "Registros: {n} reenvío(s) de inventario no llegaron a GLPI (red / DNS / tiempo) (último: {last}, {files})",
                        "Logs: {n} Inventarweiterleitung(en) haben GLPI nicht erreicht (Netz / DNS / Timeout) (zuletzt: {last}, {files})"),
    "hint_log_forward_net": ("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"),
    "log_tls": ("Logs: {n} TLS certificate error(s) (last: {last}, {files})", "Journaux : {n} erreur(s) de certificat TLS (dernière : {last}, {files})",
                "Registros: {n} error(es) de certificado TLS (último: {last}, {files})", "Logs: {n} TLS-Zertifikatsfehler (zuletzt: {last}, {files})"),
    "hint_log_tls": ("The GLPI certificate is not trusted by the Medulla server: add its CA (update-ca-certificates)",
                     "Le certificat de GLPI n'est pas reconnu par le serveur Medulla : ajoutez son AC (update-ca-certificates)",
                     "El certificado de GLPI no es reconocido por el servidor Medulla: añada su CA (update-ca-certificates)",
                     "Das GLPI-Zertifikat ist dem Medulla-Server nicht bekannt: CA hinzufügen (update-ca-certificates)"),
    "log_federated": ("Logs: {n} federated-table error(s) (Medulla → GLPI) (last: {last}, {files})",
                      "Journaux : {n} erreur(s) des tables fédérées (Medulla → GLPI) (dernière : {last}, {files})",
                      "Registros: {n} error(es) de tablas federadas (Medulla → GLPI) (último: {last}, {files})",
                      "Logs: {n} Fehler der föderierten Tabellen (Medulla → GLPI) (zuletzt: {last}, {files})"),
    "hint_log_federated": ("The server itsm_federated cannot reach the GLPI database: see « Federated tables » above",
                           "Le serveur itsm_federated ne joint pas la base GLPI : voir « Tables fédérées » plus haut",
                           "El servidor itsm_federated no alcanza la BD de GLPI: vea « Tablas federadas » más arriba",
                           "Der Server itsm_federated erreicht die GLPI-Datenbank nicht: siehe „Föderierte Tabellen“ oben"),
    "log_db_denied": ("Logs: {n} database access denial(s) (last: {last}, {files})", "Journaux : {n} refus d'accès à une base (dernier : {last}, {files})",
                      "Registros: {n} acceso(s) denegado(s) a una BD (último: {last}, {files})", "Logs: {n} verweigerte Datenbankzugriffe (zuletzt: {last}, {files})"),
    "hint_log_db_denied": ("Wrong user / password, or user not allowed from the Medulla IP: compare with the GLPI database checks above",
                           "Utilisateur / mot de passe erroné, ou utilisateur non autorisé depuis l'IP de Medulla : comparez avec les contrôles de la base GLPI plus haut",
                           "Usuario / contraseña incorrectos, o usuario no permitido desde la IP de Medulla: compare con las verificaciones de la BD de GLPI",
                           "Falscher Benutzer / Passwort oder Benutzer von der Medulla-IP nicht zugelassen: mit den GLPI-DB-Prüfungen oben vergleichen"),
    "log_db_unreachable": ("Logs: {n} database connection loss(es) (last: {last}, {files})",
                           "Journaux : {n} perte(s) de connexion à une base (dernière : {last}, {files})",
                           "Registros: {n} pérdida(s) de conexión a una BD (último: {last}, {files})",
                           "Logs: {n} Datenbank-Verbindungsabbrüche (zuletzt: {last}, {files})"),
    "hint_log_db_unreachable": ("Network, firewall or GLPI DB server restart/overload at that time",
                                "Réseau, pare-feu, ou redémarrage / surcharge du serveur de base GLPI à ce moment",
                                "Red, cortafuegos, o reinicio / sobrecarga del servidor de BD de GLPI en ese momento",
                                "Netzwerk, Firewall oder Neustart / Überlastung des GLPI-DB-Servers zu diesem Zeitpunkt"),
    "log_db_schema": ("Logs: {n} SQL error(s) on missing tables / columns / views (last: {last}, {files})",
                      "Journaux : {n} erreur(s) SQL sur des tables / colonnes / vues absentes (dernière : {last}, {files})",
                      "Registros: {n} error(es) SQL en tablas / columnas / vistas ausentes (último: {last}, {files})",
                      "Logs: {n} SQL-Fehler wegen fehlender Tabellen / Spalten / Views (zuletzt: {last}, {files})"),
    "hint_log_db_schema": ("Medulla views missing or out of date in GLPI (glpi-100.sql / glpi-110.sql), or Medulla / GLPI version mismatch",
                           "Vues Medulla absentes ou périmées dans GLPI (glpi-100.sql / glpi-110.sql), ou versions Medulla / GLPI incompatibles",
                           "Vistas de Medulla ausentes u obsoletas en GLPI (glpi-100.sql / glpi-110.sql), o versiones Medulla / GLPI incompatibles",
                           "Medulla-Views in GLPI fehlen oder sind veraltet (glpi-100.sql / glpi-110.sql), oder Medulla- / GLPI-Versionen passen nicht"),
    "log_api": ("Logs: {n} GLPI REST API error(s) (last: {last}, {files})", "Journaux : {n} erreur(s) de l'API REST GLPI (dernière : {last}, {files})",
                "Registros: {n} error(es) de la API REST de GLPI (último: {last}, {files})", "Logs: {n} Fehler der GLPI-REST-API (zuletzt: {last}, {files})"),
    "hint_log_api": ("Tokens / API client / IP range: see « GLPI REST API » above", "Jetons / client API / plage IP : voir « API REST GLPI » plus haut",
                     "Tokens / cliente API / rango IP: vea « API REST de GLPI » más arriba", "Tokens / API-Client / IP-Bereich: siehe „GLPI-REST-API“ oben"),
    "log_plugin": ("Logs: {n} inventory(ies) sent while the GLPI inventory plugin was missing or disabled (last: {last}, {files})",
                   "Journaux : {n} inventaire(s) envoyé(s) alors que le plugin d'inventaire GLPI était absent ou désactivé (dernier : {last}, {files})",
                   "Registros: {n} inventario(s) enviado(s) con el plugin de inventario de GLPI ausente o desactivado (último: {last}, {files})",
                   "Logs: {n} Inventar(e) gesendet, während das GLPI-Inventar-Plugin fehlte oder deaktiviert war (zuletzt: {last}, {files})"),
    "hint_log_plugin": ("GLPI: Setup > Plugins", "GLPI : Configuration > Plugins", "GLPI: Configuración > Plugins", "GLPI: Einrichten > Plugins"),
    "log_no_uuid": ("Logs: {n} machine(s) without a GLPI inventory after injection (last: {last}, {files})",
                    "Journaux : {n} machine(s) sans inventaire GLPI après injection (dernière : {last}, {files})",
                    "Registros: {n} equipo(s) sin inventario GLPI tras la inyección (último: {last}, {files})",
                    "Logs: {n} Maschine(n) ohne GLPI-Inventar nach der Injektion (zuletzt: {last}, {files})"),
    "hint_log_no_uuid": ("Consequence of a rejected forward (see above) or of a GLPI import rule refusing the computer",
                         "Conséquence d'une remontée rejetée (voir plus haut) ou d'une règle d'import GLPI qui refuse la machine",
                         "Consecuencia de un reenvío rechazado (ver arriba) o de una regla de importación de GLPI que rechaza el equipo",
                         "Folge einer abgelehnten Weiterleitung (siehe oben) oder einer GLPI-Importregel, die den Computer ablehnt"),

    # Diagnostic archive
    "sec_collect": ("Diagnostic archive", "Archive de diagnostic", "Archivo de diagnóstico", "Diagnosearchiv"),
    "collect_ok": ("{file} created ({n} files: logs and configuration, passwords and tokens masked)",
                   "{file} créé ({n} fichiers : journaux et configuration, mots de passe et jetons masqués)",
                   "{file} creado ({n} archivos: registros y configuración, contraseñas y tokens ocultos)",
                   "{file} erstellt ({n} Dateien: Logs und Konfiguration, Passwörter und Tokens maskiert)"),
    "collect_note": ("Check its content before sending it: the logs contain machine names and IP addresses",
                     "Vérifiez son contenu avant envoi : les journaux contiennent des noms de machines et des adresses IP",
                     "Revise su contenido antes de enviarlo: los registros contienen nombres de equipos y direcciones IP",
                     "Inhalt vor dem Versand prüfen: die Logs enthalten Rechnernamen und IP-Adressen"),
    "collect_ko": ("Cannot build the diagnostic archive: {err}", "Création de l'archive de diagnostic impossible : {err}",
                   "No se puede crear el archivo de diagnóstico: {err}", "Diagnosearchiv kann nicht erstellt werden: {err}"),

    # Configuration read on the Medulla server
    "sec_config": ("Configuration read on the Medulla server", "Configuration lue sur le serveur Medulla",
                   "Configuración leída en el servidor Medulla", "Auf dem Medulla-Server gelesene Konfiguration"),
    "cfg_intro": ("Effective values (base file + .local, substitute defaults when a key is missing); source in brackets",
                  "Valeurs effectives (fichier de base + .local, valeurs par défaut du substitut si une clé manque) ; source entre parenthèses",
                  "Valores efectivos (archivo base + .local, valores por defecto del sustituto si falta una clave); origen entre paréntesis",
                  "Wirksame Werte (Basisdatei + .local, Substitut-Standardwerte bei fehlendem Schlüssel); Quelle in Klammern"),
    "cfg_client_agent": ("Medulla agent (clients)", "Agent Medulla (postes)", "Agente Medulla (equipos)", "Medulla-Agent (Clients)"),
    "cfg_injection_mode": ("Inventory injection mode of the substitute (inventory_injection_mode): {mode}",
                           "Mode d'injection des inventaires du substitut (inventory_injection_mode) : {mode}",
                           "Modo de inyección de inventarios del sustituto (inventory_injection_mode): {mode}",
                           "Inventar-Injektionsmodus des Substituts (inventory_injection_mode): {mode}"),
    "cfg_module_readonly": ("inventory_injection_mode = {mode} writes directly into the GLPI database, but Medulla's access is read-only",
                            "inventory_injection_mode = {mode} écrit directement dans la base GLPI, mais l'accès de Medulla est en lecture seule",
                            "inventory_injection_mode = {mode} escribe directamente en la BD de GLPI, pero el acceso de Medulla es de solo lectura",
                            "inventory_injection_mode = {mode} schreibt direkt in die GLPI-Datenbank, Medullas Zugriff ist aber nur lesend"),
    "hint_cfg_module_readonly": ("Use inventory_injection_mode = forward, or give write access to the GLPI database",
                                 "Utilisez inventory_injection_mode = forward, ou donnez l'accès en écriture à la base GLPI",
                                 "Use inventory_injection_mode = forward, o conceda acceso de escritura a la BD de GLPI",
                                 "inventory_injection_mode = forward verwenden oder Schreibzugriff auf die GLPI-Datenbank geben"),
    "cfg_no_injection": ("enable_forward = False with inventory_injection_mode = forward: received inventories go nowhere",
                         "enable_forward = False avec inventory_injection_mode = forward : les inventaires reçus ne vont nulle part",
                         "enable_forward = False con inventory_injection_mode = forward: los inventarios recibidos no van a ninguna parte",
                         "enable_forward = False mit inventory_injection_mode = forward: empfangene Inventare gehen nirgendwohin"),
    "hint_cfg_no_injection": ("Enable forwarding (fix mode), or use read-only mode if GLPI gets inventories from its own agents",
                              "Activez la remontée (mode correction), ou passez en lecture seule si GLPI reçoit les inventaires de ses propres agents",
                              "Active el reenvío (modo corrección), o use solo lectura si GLPI recibe los inventarios de sus propios agentes",
                              "Weiterleitung aktivieren (Korrekturmodus) oder Nur-Lese-Modus, wenn GLPI die Inventare von eigenen Agenten erhält"),
    "cfg_db_ssl": ("glpi.ini enables TLS to the GLPI database: the substitutes and the federated tables connect without TLS",
                   "glpi.ini active TLS vers la base GLPI : les substituts et les tables fédérées se connectent sans TLS",
                   "glpi.ini activa TLS hacia la BD de GLPI: los sustitutos y las tablas federadas se conectan sin TLS",
                   "glpi.ini aktiviert TLS zur GLPI-Datenbank: die Substitute und die föderierten Tabellen verbinden sich ohne TLS"),
    "hint_cfg_db_ssl": ("The GLPI database must also accept non-TLS connections from the Medulla IP (no require_secure_transport, no REQUIRE SSL)",
                        "La base GLPI doit aussi accepter les connexions sans TLS depuis l'IP de Medulla (pas de require_secure_transport, pas de REQUIRE SSL)",
                        "La BD de GLPI debe aceptar también conexiones sin TLS desde la IP de Medulla (sin require_secure_transport ni REQUIRE SSL)",
                        "Die GLPI-Datenbank muss auch Verbindungen ohne TLS von der Medulla-IP annehmen (kein require_secure_transport, kein REQUIRE SSL)"),
    "cfg_url_differs": ("glpi.ini: {opt} points to {value}, the GLPI web URL is {url}",
                        "glpi.ini : {opt} pointe vers {value}, l'URL web de GLPI est {url}",
                        "glpi.ini: {opt} apunta a {value}, la URL web de GLPI es {url}",
                        "glpi.ini: {opt} zeigt auf {value}, die GLPI-Web-URL ist {url}"),
    "cfg_forward_other_host": ("url_to_forward {url} is not on the same host / port as the GLPI web URL {web}",
                               "url_to_forward {url} n'est pas sur le même hôte / port que l'URL web de GLPI {web}",
                               "url_to_forward {url} no está en el mismo host / puerto que la URL web de GLPI {web}",
                               "url_to_forward {url} liegt nicht auf demselben Host / Port wie die GLPI-Web-URL {web}"),
    "cfg_agent_inventory_disabled": ("{file}: the Medulla agent installer is generated without the inventory agent (--disable-inventory)",
                                     "{file} : l'installeur de l'agent Medulla est généré sans agent d'inventaire (--disable-inventory)",
                                     "{file}: el instalador del agente Medulla se genera sin agente de inventario (--disable-inventory)",
                                     "{file}: der Medulla-Agent-Installer wird ohne Inventar-Agent erzeugt (--disable-inventory)"),
    "conf_mismatch_inactive": ("{file}: values differ from glpi.ini.local ({keys}) — {svc} is neither enabled nor running",
                               "{file} : valeurs différentes de glpi.ini.local ({keys}) — {svc} n'est ni activé ni démarré",
                               "{file}: valores distintos de glpi.ini.local ({keys}) — {svc} no está habilitado ni en ejecución",
                               "{file}: Werte weichen von glpi.ini.local ab ({keys}) — {svc} ist weder aktiviert noch gestartet"),
    "hint_conf_defaults": ("Not set in the file, so the substitute uses its default (local GLPI, mmc/mmc): {keys}",
                           "Absentes du fichier, le substitut utilise donc sa valeur par défaut (GLPI local, mmc/mmc) : {keys}",
                           "Ausentes del archivo, el sustituto usa su valor por defecto (GLPI local, mmc/mmc): {keys}",
                           "In der Datei nicht gesetzt, der Substitut nutzt seinen Standardwert (lokales GLPI, mmc/mmc): {keys}"),
    "forward_module_mode": ("inventory_injection_mode = module: inventories are written directly into the GLPI database, no HTTP forward to test",
                            "inventory_injection_mode = module : les inventaires sont écrits directement dans la base GLPI, pas de remontée HTTP à tester",
                            "inventory_injection_mode = module: los inventarios se escriben directamente en la BD de GLPI, no hay reenvío HTTP que probar",
                            "inventory_injection_mode = module: Inventare werden direkt in die GLPI-Datenbank geschrieben, keine HTTP-Weiterleitung zu prüfen"),
    "plan_update_glpidb": ("update [glpidatabase] in {file}", "mise à jour de [glpidatabase] dans {file}",
                           "actualización de [glpidatabase] en {file}", "Aktualisierung von [glpidatabase] in {file}"),
    "lbl_inv_mode": ("Inventory injection mode", "Mode d'injection des inventaires", "Modo de inyección de inventarios",
                     "Inventar-Injektionsmodus"),
    "lbl_db_ssl": ("TLS to the GLPI database (CA)", "TLS vers la base GLPI (AC)", "TLS hacia la BD de GLPI (CA)",
                   "TLS zur GLPI-Datenbank (CA)"),

    # V5: alignment with the Medulla installer
    "cfg_remote_title": ("Substitutes declared in xmppmaster.substituteconf, configured on another server",
                         "Substituts déclarés dans xmppmaster.substituteconf, configurés sur un autre serveur",
                         "Sustitutos declarados en xmppmaster.substituteconf, configurados en otro servidor",
                         "In xmppmaster.substituteconf deklarierte Substitute, auf einem anderen Server konfiguriert"),
    "cfg_remote_substitutes": ("{n} substitute(s) run on another server: {list}",
                               "{n} substitut(s) tourne(nt) sur un autre serveur : {list}",
                               "{n} sustituto(s) se ejecuta(n) en otro servidor: {list}",
                               "{n} Substitut(e) laufen auf einem anderen Server: {list}"),
    "hint_cfg_remote_substitutes": ("Their [glpidatabase] and url_to_forward are on that server: check them there (this script only sees this server)",
                                    "Leurs [glpidatabase] et url_to_forward sont sur ce serveur : vérifiez-les là-bas (ce script ne voit que ce serveur)",
                                    "Sus [glpidatabase] y url_to_forward están en ese servidor: verifíquelos allí (este script solo ve este servidor)",
                                    "Deren [glpidatabase] und url_to_forward liegen auf jenem Server: dort prüfen (dieses Skript sieht nur diesen Server)"),
    "cfg_inv_differs": ("{file} forwards differently from {ref} ({keys})", "{file} remonte différemment de {ref} ({keys})",
                        "{file} reenvía de forma distinta a {ref} ({keys})", "{file} leitet anders weiter als {ref} ({keys})"),
    "cfg_inv_same": ("{file}: same forward settings as {ref}", "{file} : mêmes réglages de remontée que {ref}",
                     "{file}: mismos ajustes de reenvío que {ref}", "{file}: gleiche Weiterleitungseinstellungen wie {ref}"),
    "cfg_no_inv_substitute": ("No inventory substitute configured in {dir} on this server",
                              "Aucun substitut d'inventaire configuré dans {dir} sur ce serveur",
                              "Ningún sustituto de inventario configurado en {dir} en este servidor",
                              "Kein Inventar-Substitut in {dir} auf diesem Server konfiguriert"),
    "fed_wrapper": ("Federated server wrapper: {wrapper}", "Connecteur du serveur fédéré : {wrapper}",
                    "Conector del servidor federado: {wrapper}", "Wrapper des föderierten Servers: {wrapper}"),
    "fed_wrapper_retry": ("The 'mariadb' wrapper cannot read GLPI ({err}): retrying with 'mysql', as the Medulla installer does",
                          "Le connecteur 'mariadb' ne lit pas GLPI ({err}) : nouvel essai avec 'mysql', comme l'installeur Medulla",
                          "El conector 'mariadb' no lee GLPI ({err}): nuevo intento con 'mysql', como el instalador de Medulla",
                          "Der Wrapper 'mariadb' liest GLPI nicht ({err}): neuer Versuch mit 'mysql', wie der Medulla-Installer"),
    "fed_wrapper_mysql_ok": ("Federated server recreated with the 'mysql' wrapper: GLPI readable",
                             "Serveur fédéré recréé avec le connecteur 'mysql' : GLPI lisible",
                             "Servidor federado recreado con el conector 'mysql': GLPI legible",
                             "Föderierter Server mit dem Wrapper 'mysql' neu angelegt: GLPI lesbar"),
    "hint_forward_installer_default": ("/glpi/ comes from the Medulla installer default for a local GLPI (ITSM_BASEURL = http://<server>/glpi): an external GLPI installed at the site root needs ITSM_BASEURL / ITSM_FORWARD_URLINVENTORY redefined",
                                       "/glpi/ vient de la valeur par défaut de l'installeur Medulla pour un GLPI local (ITSM_BASEURL = http://<serveur>/glpi) : un GLPI externe installé à la racine du site impose de redéfinir ITSM_BASEURL / ITSM_FORWARD_URLINVENTORY",
                                       "/glpi/ proviene del valor por defecto del instalador de Medulla para un GLPI local (ITSM_BASEURL = http://<servidor>/glpi): un GLPI externo en la raíz del sitio exige redefinir ITSM_BASEURL / ITSM_FORWARD_URLINVENTORY",
                                       "/glpi/ stammt vom Standardwert des Medulla-Installers für ein lokales GLPI (ITSM_BASEURL = http://<Server>/glpi): ein externes GLPI im Wurzelverzeichnis erfordert die Neudefinition von ITSM_BASEURL / ITSM_FORWARD_URLINVENTORY"),

    # V6: API client
    "apiclient_found_token": ("API client using the configured App-Token: {name}",
                              "Client API utilisant l'App-Token configuré : {name}",
                              "Cliente API que usa el App-Token configurado: {name}",
                              "API-Client mit dem konfigurierten App-Token: {name}"),
    "apiclient_not_identified": ("No API client named {name} and none holding the configured App-Token in clear (clients: {list})",
                                 "Aucun client API nommé {name} ni détenant en clair l'App-Token configuré (clients : {list})",
                                 "Ningún cliente API llamado {name} ni con el App-Token configurado en claro (clientes: {list})",
                                 "Kein API-Client namens {name} und keiner mit dem konfigurierten App-Token im Klartext (Clients: {list})"),
    "hint_apiclient_not_identified": ("Not an error by itself for an external GLPI: the REST API test below is authoritative",
                                      "Pas une erreur en soi pour un GLPI externe : le test de l'API REST plus bas fait foi",
                                      "No es un error en sí para un GLPI externo: la prueba de la API REST más abajo es la referencia",
                                      "Bei einem externen GLPI an sich kein Fehler: maßgeblich ist der REST-API-Test weiter unten"),

    "cfg_unreadable": ("{n} configuration file(s) unreadable by this account: {list} — their values could not be checked",
                     "{n} fichier(s) de configuration illisible(s) pour ce compte : {list} — leurs valeurs n'ont pas pu être vérifiées",
                     "{n} archivo(s) de configuración no legible(s) para esta cuenta: {list} — sus valores no se pudieron verificar",
                     "{n} Konfigurationsdatei(en) für dieses Konto nicht lesbar: {list} — ihre Werte konnten nicht geprüft werden"),
    "hint_run_as_root": ("Run the check as root for a complete diagnosis: {cmd}",
                       "Relancez la vérification en root pour un diagnostic complet : {cmd}",
                       "Vuelva a lanzar la verificación como root para un diagnóstico completo: {cmd}",
                       "Prüfung als root wiederholen, um eine vollständige Diagnose zu erhalten: {cmd}"),
    "fed_priv_unverified": ("{user} cannot create the federated server, and root could not be tried (script not run as root): fix mode, which runs as root, will use it",
                          "{user} ne peut pas créer le serveur fédéré, et root n'a pas pu être essayé (script non lancé en root) : le mode correction, lancé en root, l'utilisera",
                          "{user} no puede crear el servidor federado, y root no se pudo probar (script no lanzado como root): el modo corrección, lanzado como root, lo usará",
                          "{user} kann den föderierten Server nicht anlegen, root konnte nicht getestet werden (Skript nicht als root): der Korrekturmodus läuft als root und nutzt ihn"),
    "fedserver_unverified": ("Federated server definition (mysql.servers) only readable by root: not compared",
                           "Définition du serveur fédéré (mysql.servers) lisible seulement en root : non comparée",
                           "Definición del servidor federado (mysql.servers) legible solo como root: no comparada",
                           "Definition des föderierten Servers (mysql.servers) nur als root lesbar: nicht verglichen"),
    "log_unreadable_n": ("{n} log(s) unreadable by this account, not analysed: {list}",
                       "{n} journal(aux) illisible(s) pour ce compte, non analysé(s) : {list}",
                       "{n} registro(s) no legible(s) para esta cuenta, no analizado(s): {list}",
                       "{n} Log(s) für dieses Konto nicht lesbar, nicht ausgewertet: {list}"),
    "log_other_modules": ("{n} error(s) ({k} distinct) in logs of other Medulla modules, not related to GLPI: {files} (details: --all-errors)",
                        "{n} erreur(s) ({k} distincte(s)) dans les journaux d'autres modules Medulla, sans rapport avec GLPI : {files} (détail : --all-errors)",
                        "{n} error(es) ({k} distinto(s)) en registros de otros módulos de Medulla, sin relación con GLPI: {files} (detalle: --all-errors)",
                        "{n} Fehler ({k} verschiedene) in Logs anderer Medulla-Module, ohne Bezug zu GLPI: {files} (Details: --all-errors)"),
    "log_clean_itsm": ("No error related to GLPI in the logs of the last {h} h",
                     "Aucune erreur liée à GLPI dans les journaux des dernières {h} h",
                     "Ningún error relacionado con GLPI en los registros de las últimas {h} h",
                     "Kein GLPI-bezogener Fehler in den Logs der letzten {h} h"),
    "service_unused": ("{svc}: neither enabled nor running on this server — not checked",
                     "{svc} : ni activé ni démarré sur ce serveur — non contrôlé",
                     "{svc}: ni habilitado ni en ejecución en este servidor — no se verifica",
                     "{svc}: auf diesem Server weder aktiviert noch gestartet — nicht geprüft"),
    "api_target": ("API URL {url} (from {src})", "URL d'API {url} (de {src})", "URL de API {url} (de {src})", "API-URL {url} (aus {src})"),
    "api_url_http": ("{url} ({src}) uses plain HTTP while GLPI is served in HTTPS: tokens travel in clear on the network (whether it works: see the test below)",
                   "{url} ({src}) est en HTTP alors que GLPI est servi en HTTPS : les jetons circulent en clair sur le réseau (fonctionnement : voir le test ci-dessous)",
                   "{url} ({src}) usa HTTP mientras GLPI se sirve en HTTPS: los tokens viajan en claro por la red (funcionamiento: ver la prueba siguiente)",
                   "{url} ({src}) nutzt HTTP, GLPI wird aber per HTTPS bereitgestellt: Tokens werden im Netz im Klartext übertragen (ob es funktioniert: siehe Test unten)"),
    "forward_url_legacy": ("Legacy FusionInventory endpoint kept by the glpiinventory plugin: it works; GLPI's native URL is {expected}",
                         "Point d'entrée hérité de FusionInventory, conservé par le plugin glpiinventory : il fonctionne ; l'URL native de GLPI est {expected}",
                         "Punto de entrada heredado de FusionInventory, conservado por el plugin glpiinventory: funciona; la URL nativa de GLPI es {expected}",
                         "Alter FusionInventory-Endpunkt, vom Plugin glpiinventory beibehalten: er funktioniert; die native GLPI-URL ist {expected}"),
    "forward_url_differs_ok": ("The forward URL works; GLPI's native URL would be {expected}",
                             "L'URL de remontée fonctionne ; l'URL native de GLPI serait {expected}",
                             "La URL de reenvío funciona; la URL nativa de GLPI sería {expected}",
                             "Die Weiterleitungs-URL funktioniert; die native GLPI-URL wäre {expected}"),
    "selfservice_ok": ("GLPI profile used by Medulla for the accounts it creates: {name}",
                     "Profil GLPI utilisé par Medulla pour les comptes qu'il crée : {name}",
                     "Perfil de GLPI usado por Medulla para las cuentas que crea: {name}",
                     "GLPI-Profil, das Medulla für die angelegten Konten verwendet: {name}"),
    "selfservice_missing": ("No GLPI profile named Self-Service (simplified-interface profiles: {list}): Medulla cannot create the GLPI account of a console user who has none; limited impact — the login goes on, and such an account would get no Medulla rights unless Self-Service is in profiles_order",
                          "Aucun profil GLPI nommé Self-Service (profils à interface simplifiée : {list}) : Medulla ne peut pas créer le compte GLPI d'un utilisateur de la console qui n'en a pas ; impact limité — la connexion continue, et ce compte n'aurait aucun droit dans Medulla tant que Self-Service n'est pas dans profiles_order",
                          "Ningún perfil de GLPI llamado Self-Service (perfiles de interfaz simplificada: {list}): Medulla no puede crear la cuenta GLPI de un usuario de la consola que no la tenga; impacto limitado — el inicio de sesión continúa, y esa cuenta no tendría ningún derecho en Medulla mientras Self-Service no esté en profiles_order",
                          "Kein GLPI-Profil namens Self-Service (Profile mit vereinfachter Oberfläche: {list}): Medulla kann für einen Konsolenbenutzer ohne GLPI-Konto keines anlegen; begrenzte Auswirkung — die Anmeldung läuft weiter, und ein solches Konto hätte in Medulla keine Rechte, solange Self-Service nicht in profiles_order steht"),
    "log_selfservice": ("Logs: {n} GLPI account creation(s) failed, no Self-Service profile (last: {last}, {files})",
                      "Journaux : {n} création(s) de compte GLPI en échec, pas de profil Self-Service (dernière : {last}, {files})",
                      "Registros: {n} creación(es) de cuenta GLPI fallida(s), sin perfil Self-Service (último: {last}, {files})",
                      "Logs: {n} GLPI-Kontoanlage(n) fehlgeschlagen, kein Self-Service-Profil (zuletzt: {last}, {files})"),
    "hint_log_selfservice": ("See « GLPI API client and user » above: profile check", "Voir « Client et utilisateur API GLPI » plus haut : contrôle des profils",
                           "Vea « Cliente y usuario API de GLPI » más arriba: verificación de perfiles", "Siehe „GLPI-API-Client und -Benutzer“ oben: Profilprüfung"),
    "log_mmc_plugin": ("Logs: mmc-agent failed to load its admin / glpi plugin ({n} time(s), last: {last}, {files})",
                     "Journaux : mmc-agent n'a pas pu charger son plugin admin / glpi ({n} fois, dernière : {last}, {files})",
                     "Registros: mmc-agent no pudo cargar su plugin admin / glpi ({n} vez/veces, último: {last}, {files})",
                     "Logs: mmc-agent konnte sein Plugin admin / glpi nicht laden ({n}-mal, zuletzt: {last}, {files})"),
    "hint_log_mmc_plugin": ("The admin plugin holds saas_application (GLPI API settings): without it the console cannot call the GLPI API. Check the database settings in /etc/mmc/plugins/admin.ini(.local), then restart mmc-agent",
                          "Le plugin admin porte saas_application (paramètres de l'API GLPI) : sans lui, la console ne peut pas appeler l'API GLPI. Vérifiez la base dans /etc/mmc/plugins/admin.ini(.local), puis redémarrez mmc-agent",
                          "El plugin admin contiene saas_application (parámetros de la API de GLPI): sin él, la consola no puede llamar a la API de GLPI. Revise la BD en /etc/mmc/plugins/admin.ini(.local) y reinicie mmc-agent",
                          "Das Plugin admin enthält saas_application (GLPI-API-Einstellungen): ohne es kann die Konsole die GLPI-API nicht aufrufen. Datenbank in /etc/mmc/plugins/admin.ini(.local) prüfen, dann mmc-agent neu starten"),
    "log_since_start": ("This happened during the current run of mmc-agent (started {start})",
                      "C'est arrivé pendant l'exécution actuelle de mmc-agent (démarré le {start})",
                      "Ocurrió durante la ejecución actual de mmc-agent (iniciado el {start})",
                      "Das geschah im aktuellen Lauf von mmc-agent (gestartet am {start})"),
    "log_before_start": ("before the last start of mmc-agent ({start}): no longer current",
                       "avant le dernier démarrage de mmc-agent ({start}) : plus d'actualité",
                       "antes del último inicio de mmc-agent ({start}): ya no es actual",
                       "vor dem letzten Start von mmc-agent ({start}): nicht mehr aktuell"),
    "sec_admin_plugin": ("mmc-agent admin plugin (saas_application)", "Plugin admin de mmc-agent (saas_application)",
                       "Plugin admin de mmc-agent (saas_application)", "mmc-agent-Plugin admin (saas_application)"),
    "admin_disabled": ("{file}: the admin plugin is disabled — the console cannot use the GLPI API settings of saas_application",
                     "{file} : le plugin admin est désactivé — la console ne peut pas utiliser les paramètres API GLPI de saas_application",
                     "{file}: el plugin admin está desactivado — la consola no puede usar los parámetros API de GLPI de saas_application",
                     "{file}: das Plugin admin ist deaktiviert — die Konsole kann die GLPI-API-Einstellungen aus saas_application nicht nutzen"),
    "hint_admin_disabled": ("[main] disable = 0 in /etc/mmc/plugins/admin.ini.local, then restart mmc-agent",
                          "[main] disable = 0 dans /etc/mmc/plugins/admin.ini.local, puis redémarrez mmc-agent",
                          "[main] disable = 0 en /etc/mmc/plugins/admin.ini.local, y reinicie mmc-agent",
                          "[main] disable = 0 in /etc/mmc/plugins/admin.ini.local, dann mmc-agent neu starten"),
    "admin_db_target": ("Admin database used by the plugin: {user}@{host}:{port}/{db} ({file})",
                      "Base admin utilisée par le plugin : {user}@{host}:{port}/{db} ({file})",
                      "BD admin usada por el plugin: {user}@{host}:{port}/{db} ({file})",
                      "Vom Plugin genutzte Admin-Datenbank: {user}@{host}:{port}/{db} ({file})"),
    "admin_db_conn_ko": ("Admin database unreachable with the plugin settings: {err}",
                       "Base admin inaccessible avec les paramètres du plugin : {err}",
                       "BD admin inaccesible con los parámetros del plugin: {err}",
                       "Admin-Datenbank mit den Plugin-Einstellungen nicht erreichbar: {err}"),
    "hint_admin_conf": ("Check [database] in {file}", "Vérifiez [database] dans {file}", "Revise [database] en {file}",
                      "[database] in {file} prüfen"),
    "admin_tables_ok": ("The {n} tables used by the admin plugin are present", "Les {n} tables utilisées par le plugin admin sont présentes",
                      "Las {n} tablas usadas por el plugin admin están presentes", "Die {n} vom Plugin admin genutzten Tabellen sind vorhanden"),
    "admin_tables_missing": ("Admin database: missing table(s) needed by the plugin: {list}",
                           "Base admin : table(s) nécessaire(s) au plugin absente(s) : {list}",
                           "BD admin: falta(n) tabla(s) necesaria(s) para el plugin: {list}",
                           "Admin-Datenbank: vom Plugin benötigte Tabelle(n) fehlen: {list}"),
    "admin_version_none": ("Admin database: no schema version (table version empty or missing)",
                         "Base admin : aucune version de schéma (table version vide ou absente)",
                         "BD admin: sin versión de esquema (tabla version vacía o ausente)",
                         "Admin-Datenbank: keine Schemaversion (Tabelle version leer oder fehlend)"),
    "admin_version_only": ("Admin database schema version: {v} (schema files not found to compare)",
                         "Version du schéma de la base admin : {v} (fichiers de schéma introuvables pour comparer)",
                         "Versión del esquema de la BD admin: {v} (archivos de esquema no encontrados para comparar)",
                         "Schemaversion der Admin-Datenbank: {v} (Schemadateien zum Vergleich nicht gefunden)"),
    "admin_version_ok": ("Admin database schema up to date (version {v})", "Schéma de la base admin à jour (version {v})",
                       "Esquema de la BD admin al día (versión {v})", "Schema der Admin-Datenbank aktuell (Version {v})"),
    "admin_version_old": ("Admin database schema {v} older than the installed files ({exp}): mmc-agent tries to update it at start, and the admin plugin is not loaded if that fails",
                        "Schéma de la base admin en version {v}, plus ancien que les fichiers installés ({exp}) : mmc-agent tente la mise à jour au démarrage, et le plugin admin n'est pas chargé si elle échoue",
                        "Esquema de la BD admin en versión {v}, más antiguo que los archivos instalados ({exp}): mmc-agent intenta actualizarlo al arrancar y el plugin admin no se carga si falla",
                        "Schema der Admin-Datenbank Version {v}, älter als die installierten Dateien ({exp}): mmc-agent versucht beim Start zu aktualisieren, schlägt das fehl, wird das Plugin admin nicht geladen"),
    "admin_version_newer": ("Admin database schema {v} newer than the installed files ({exp}): the admin plugin refuses to start",
                          "Schéma de la base admin en version {v}, plus récent que les fichiers installés ({exp}) : le plugin admin refuse de démarrer",
                          "Esquema de la BD admin en versión {v}, más reciente que los archivos instalados ({exp}): el plugin admin no arranca",
                          "Schema der Admin-Datenbank Version {v}, neuer als die installierten Dateien ({exp}): das Plugin admin startet nicht"),
    "hint_admin_schema": ("Medulla packages and admin database out of step: check the last Medulla update (update_medulla.sh) and mmc-agent.log at start",
                        "Paquets Medulla et base admin désynchronisés : vérifiez la dernière mise à jour de Medulla (update_medulla.sh) et mmc-agent.log au démarrage",
                        "Paquetes de Medulla y BD admin desincronizados: revise la última actualización de Medulla (update_medulla.sh) y mmc-agent.log al arrancar",
                        "Medulla-Pakete und Admin-Datenbank nicht synchron: letztes Medulla-Update (update_medulla.sh) und mmc-agent.log beim Start prüfen"),
    "log_cause": ("Cause logged just before: {line}", "Cause journalisée juste avant : {line}", "Causa registrada justo antes: {line}",
                "Unmittelbar davor protokollierte Ursache: {line}"),
    "log_no_cause": ("No database error about this plugin logged just before",
                     "Aucune erreur de base concernant ce plugin journalisée juste avant",
                     "Ningún error de BD sobre este plugin registrado justo antes",
                     "Kein Datenbankfehler zu diesem Plugin unmittelbar davor protokolliert"),
    "admin_tables_optional": ("Admin database: table(s) missing, used by console features (not blocking the plugin start): {list}",
                              "Base admin : table(s) absente(s), utilisée(s) par des fonctions de la console (sans bloquer le démarrage du plugin) : {list}",
                              "BD admin: falta(n) tabla(s) usada(s) por funciones de la consola (no impide el arranque del plugin): {list}",
                              "Admin-Datenbank: fehlende Tabelle(n), von Konsolenfunktionen genutzt (verhindert den Plugin-Start nicht): {list}"),
    "log_schema_updated_restart": ("Diagnosis: at that start mmc-agent found the admin schema out of date and updated it; the plugin was not loaded during that run, but the schema is up to date now — restart mmc-agent (systemctl restart mmc-agent) and check again",
                                   "Diagnostic : à ce démarrage, mmc-agent a trouvé le schéma admin en retard et l'a mis à jour ; le plugin n'a pas été chargé pendant cette exécution, mais le schéma est désormais à jour — redémarrez mmc-agent (systemctl restart mmc-agent) puis revérifiez",
                                   "Diagnóstico: en ese arranque mmc-agent encontró el esquema admin desfasado y lo actualizó; el plugin no se cargó durante esa ejecución, pero el esquema ya está al día — reinicie mmc-agent (systemctl restart mmc-agent) y vuelva a verificar",
                                   "Diagnose: bei diesem Start fand mmc-agent das admin-Schema veraltet und hat es aktualisiert; das Plugin wurde in diesem Lauf nicht geladen, das Schema ist jetzt aber aktuell — mmc-agent neu starten (systemctl restart mmc-agent) und erneut prüfen"),
    "admin_code_root": ("Installed Medulla code inspected: {root}", "Code Medulla installé examiné : {root}",
                      "Código de Medulla instalado examinado: {root}", "Installierter Medulla-Code untersucht: {root}"),
    "admin_code_none": ("Installed code: AdminDatabase.activate() returns None when the database is already activated, and the admin plugin takes that for a failure",
                      "Code installé : AdminDatabase.activate() renvoie None si la base est déjà activée, et le plugin admin prend cela pour un échec",
                      "Código instalado: AdminDatabase.activate() devuelve None si la BD ya está activada, y el plugin admin lo toma por un fallo",
                      "Installierter Code: AdminDatabase.activate() gibt None zurück, wenn die Datenbank bereits aktiviert ist, und das Plugin admin wertet das als Fehler"),
    "admin_code_activators": ("Installed code activating AdminDatabase outside the admin plugin: {list}",
                            "Code installé qui active AdminDatabase en dehors du plugin admin : {list}",
                            "Código instalado que activa AdminDatabase fuera del plugin admin: {list}",
                            "Installierter Code, der AdminDatabase außerhalb des Plugins admin aktiviert: {list}"),
    "log_admin_double_activation": ("Probable explanation: the admin database is healthy and no database error is logged — the installed code reports « not loaded » when AdminDatabase was already activated before the admin plugin (by: {list}). Medulla bug, not a server problem: the GLPI API settings stay readable from saas_application",
                                  "Explication probable : la base admin est saine et aucune erreur de base n'est journalisée — le code installé déclare « not loaded » quand AdminDatabase a déjà été activée avant le plugin admin (par : {list}). Bug Medulla, pas un problème du serveur : les paramètres API GLPI restent lisibles dans saas_application",
                                  "Explicación probable: la BD admin está sana y no se registra ningún error de BD — el código instalado declara « not loaded » cuando AdminDatabase ya se activó antes del plugin admin (por: {list}). Bug de Medulla, no un problema del servidor: los parámetros API de GLPI siguen legibles en saas_application",
                                  "Wahrscheinliche Erklärung: die Admin-Datenbank ist gesund und kein Datenbankfehler ist protokolliert — der installierte Code meldet « not loaded », wenn AdminDatabase vor dem Plugin admin bereits aktiviert wurde (durch: {list}). Medulla-Bug, kein Serverproblem: die GLPI-API-Einstellungen bleiben in saas_application lesbar"),
    "log_context": ("Lines of mmc-agent.log just before (any level):", "Lignes de mmc-agent.log juste avant (tous niveaux) :",
                  "Líneas de mmc-agent.log justo antes (todos los niveles):", "Zeilen aus mmc-agent.log unmittelbar davor (alle Stufen):"),
    "none": ("none", "aucun", "ninguno", "keiner"),
    "admin_code_conditional": ("Installed code: PluginConfig activates AdminDatabase only for a plugin configured with the « database » backend ({list}); plugins using it: {users}",
                             "Code installé : PluginConfig n'active AdminDatabase que pour un plugin configuré en mode « database » ({list}) ; plugins qui l'utilisent : {users}",
                             "Código instalado: PluginConfig solo activa AdminDatabase para un plugin configurado en modo « database » ({list}); plugins que lo usan: {users}",
                             "Installierter Code: PluginConfig aktiviert AdminDatabase nur für ein Plugin im Modus « database » ({list}); Plugins, die ihn nutzen: {users}"),
    "log_admin_unexplained": ("Cause not identified: admin database healthy, no database error logged, nothing else activates it in the installed code. mmc-agent.log level: {level} — in DEBUG the lines below show the plugin start in detail; otherwise set [handler_hand01] level = DEBUG in /etc/mmc/agent/config.ini.local, restart mmc-agent and run this check again",
                            "Cause non identifiée : base admin saine, aucune erreur de base journalisée, rien d'autre ne l'active dans le code installé. Niveau de mmc-agent.log : {level} — en DEBUG, les lignes ci-dessous détaillent le démarrage du plugin ; sinon, mettez [handler_hand01] level = DEBUG dans /etc/mmc/agent/config.ini.local, redémarrez mmc-agent et relancez cette vérification",
                            "Causa no identificada: BD admin sana, ningún error de BD registrado, nada más la activa en el código instalado. Nivel de mmc-agent.log: {level} — en DEBUG las líneas siguientes detallan el arranque del plugin; si no, ponga [handler_hand01] level = DEBUG en /etc/mmc/agent/config.ini.local, reinicie mmc-agent y repita esta verificación",
                            "Ursache nicht ermittelt: Admin-Datenbank gesund, kein Datenbankfehler protokolliert, im installierten Code aktiviert sie nichts anderes. Stufe von mmc-agent.log: {level} — in DEBUG zeigen die Zeilen unten den Plugin-Start im Detail; sonst [handler_hand01] level = DEBUG in /etc/mmc/agent/config.ini.local setzen, mmc-agent neu starten und diese Prüfung wiederholen"),
    "unexpected_error": ("Unexpected error: {err}", "Erreur inattendue : {err}", "Error inesperado: {err}", "Unerwarteter Fehler: {err}"),
    "hint_verbose": ("Run again with --verbose for the full trace", "Relancez avec --verbose pour la trace complète",
                   "Vuelva a lanzar con --verbose para la traza completa", "Mit --verbose erneut starten für die vollständige Ablaufverfolgung"),
    "admin_code_double_load": ("Installed mmc-agent loads the admin plugin twice at start (loadPlugins puts it after base without removing it from its place): the second load reports « Plugin admin not loaded » while the first one succeeded",
                             "mmc-agent installé charge le plugin admin deux fois au démarrage (loadPlugins le place après base sans le retirer de sa place) : le second chargement déclare « Plugin admin not loaded » alors que le premier a réussi",
                             "mmc-agent instalado carga el plugin admin dos veces al arrancar (loadPlugins lo coloca tras base sin quitarlo de su sitio): la segunda carga declara « Plugin admin not loaded » aunque la primera tuvo éxito",
                             "Das installierte mmc-agent lädt das Plugin admin beim Start zweimal (loadPlugins setzt es hinter base, ohne es von seiner Stelle zu entfernen): das zweite Laden meldet « Plugin admin not loaded », obwohl das erste erfolgreich war"),
    "log_admin_double_load": ("harmless: the plugin was loaded successfully just before in the same start; this second load is a Medulla bug (plugin loaded twice), the console and saas_application work",
                            "sans conséquence : le plugin a été chargé avec succès juste avant au même démarrage ; ce second chargement est un bug Medulla (plugin chargé deux fois), la console et saas_application fonctionnent",
                            "sin consecuencias: el plugin se cargó con éxito justo antes en el mismo arranque; esta segunda carga es un bug de Medulla (plugin cargado dos veces), la consola y saas_application funcionan",
                            "folgenlos: das Plugin wurde beim selben Start kurz zuvor erfolgreich geladen; dieses zweite Laden ist ein Medulla-Bug (Plugin zweimal geladen), Konsole und saas_application funktionieren"),
    "saas_url_differs_ok": ("API URL of admin.saas_application ({saas}) differs from glpi.ini.local ({ini}), but it works (API session opened with the configured tokens): nothing to change",
                          "L'URL API de admin.saas_application ({saas}) diffère de glpi.ini.local ({ini}), mais elle fonctionne (session API ouverte avec les jetons configurés) : rien à changer",
                          "La URL API de admin.saas_application ({saas}) difiere de glpi.ini.local ({ini}), pero funciona (sesión API abierta con los tokens configurados): nada que cambiar",
                          "Die API-URL in admin.saas_application ({saas}) weicht von glpi.ini.local ({ini}) ab, funktioniert aber (API-Sitzung mit den konfigurierten Tokens geöffnet): nichts zu ändern"),
    "saas_url_kept": ("API URL of admin.saas_application kept ({url}): it works", "URL API de admin.saas_application conservée ({url}) : elle fonctionne",
                    "URL API de admin.saas_application conservada ({url}): funciona", "API-URL in admin.saas_application beibehalten ({url}): sie funktioniert"),
    # Restart / reconfiguration (explicit)
    "plan_restart_ask": ("restart {list} (asked, default No)", "redémarrage de {list} (demandé, Non par défaut)",
                         "reinicio de {list} (se pregunta, No por defecto)", "Neustart von {list} (wird abgefragt, Standard: Nein)"),
    "plan_reconf_ask": ("mark every Medulla agent for reconfiguration, need_reconf=1 (asked, default No)",
                        "marquage de tous les agents Medulla pour reconfiguration, need_reconf=1 (demandé, Non par défaut)",
                        "marcado de todos los agentes Medulla para reconfiguración, need_reconf=1 (se pregunta, No por defecto)",
                        "Markierung aller Medulla-Agenten zur Neukonfiguration, need_reconf=1 (wird abgefragt, Standard: Nein)"),
    "restart_why": ("The new configuration is only used once {list} are restarted.",
                    "La nouvelle configuration n'est prise en compte qu'après redémarrage de {list}.",
                    "La nueva configuración solo se aplica tras reiniciar {list}.",
                    "Die neue Konfiguration wird erst nach einem Neustart von {list} verwendet."),
    "restart_confirm": ("Restart these services now?", "Redémarrer ces services maintenant ?",
                        "¿Reiniciar estos servicios ahora?", "Diese Dienste jetzt neu starten?"),
    "restart_skipped": ("Services not restarted: the new configuration is NOT in use yet — to apply it:",
                        "Services non redémarrés : la nouvelle configuration n'est PAS encore utilisée — pour l'appliquer :",
                        "Servicios no reiniciados: la nueva configuración AÚN no se usa — para aplicarla:",
                        "Dienste nicht neu gestartet: die neue Konfiguration ist NOCH NICHT aktiv — zum Anwenden:"),
    "reconf_why": ("need_reconf=1 makes every agent fetch its configuration again: only useful if the inventory agent changed.",
                   "need_reconf=1 force tous les agents à recharger leur configuration : utile seulement si l'agent d'inventaire a changé.",
                   "need_reconf=1 obliga a todos los agentes a recargar su configuración: solo útil si cambió el agente de inventario.",
                   "need_reconf=1 lässt alle Agenten ihre Konfiguration neu laden: nur sinnvoll, wenn sich der Inventar-Agent geändert hat."),

    # Medulla configuration
    "file_ok": ("{file} present", "{file} présent", "{file} presente", "{file} vorhanden"),
    "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_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_ok": ("GLPI 10: glpi_crypt_key is not used (only read by Medulla with GLPI 11), an empty value is normal",
                           "GLPI 10 : glpi_crypt_key n'est pas utilisée (Medulla ne la lit qu'avec GLPI 11), une valeur vide est normale",
                           "GLPI 10: glpi_crypt_key no se usa (Medulla solo la lee con GLPI 11), un valor vacío es normal",
                           "GLPI 10: glpi_crypt_key wird nicht verwendet (Medulla liest ihn nur mit GLPI 11), ein leerer Wert ist normal"),
    "cryptkey_glpi10_info": ("GLPI 10: no crypt key needed (Medulla only uses it with GLPI 11; the value stays empty)",
                             "GLPI 10 : pas de clé de chiffrement à saisir (Medulla ne l'utilise qu'avec GLPI 11 ; la valeur reste vide)",
                             "GLPI 10: no hace falta clave de cifrado (Medulla solo la usa con GLPI 11; el valor queda vacío)",
                             "GLPI 10: kein Schlüssel nötig (Medulla nutzt ihn nur mit GLPI 11; der Wert bleibt leer)"),
    "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"),
    "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}"),
    "saas_misnamed": ("saas_application: setting_name {stored} is not exactly {expected} (space, case or invisible character): Medulla does not find it — fix mode will rename it",
                      "saas_application : setting_name {stored} n'est pas exactement {expected} (espace, majuscule ou caractère invisible) : Medulla ne le trouve pas — le mode correction le renommera",
                      "saas_application: setting_name {stored} no es exactamente {expected} (espacio, mayúscula o carácter invisible): Medulla no lo encuentra — el modo corrección lo renombrará",
                      "saas_application: setting_name {stored} ist nicht genau {expected} (Leerzeichen, Großschreibung oder unsichtbares Zeichen): Medulla findet es nicht — der Korrekturmodus benennt es um"),
    "saas_value_spaces": ("saas_application: {name} only contains spaces", "saas_application : {name} ne contient que des espaces",
                          "saas_application: {name} solo contiene espacios", "saas_application: {name} enthält nur Leerzeichen"),
    "saas_renamed": ("saas_application: {stored} renamed to {expected}", "saas_application : {stored} renommé en {expected}",
                     "saas_application: {stored} renombrado a {expected}", "saas_application: {stored} umbenannt in {expected}"),
    "cryptkey_glpi11_placeholder": ("GLPI {v}: glpi_crypt_key = {value} is a placeholder — the real GLPI key is required for GLPI 11",
                                    "GLPI {v} : glpi_crypt_key = {value} est une valeur provisoire — la vraie clé GLPI est obligatoire pour GLPI 11",
                                    "GLPI {v}: glpi_crypt_key = {value} es un valor provisional — la clave real de GLPI es obligatoria para GLPI 11",
                                    "GLPI {v}: glpi_crypt_key = {value} ist ein Platzhalter — für GLPI 11 ist der echte GLPI-Schlüssel nötig"),
    "cryptkey_glpi11_required": ("GLPI {v}: the GLPI crypt key is required for GLPI 11 ({err})",
                                 "GLPI {v} : la clé de chiffrement GLPI est obligatoire pour GLPI 11 ({err})",
                                 "GLPI {v}: la clave de cifrado de GLPI es obligatoria para GLPI 11 ({err})",
                                 "GLPI {v}: der GLPI-Schlüssel ist für GLPI 11 erforderlich ({err})"),
    "cryptkey_version_unknown": ("GLPI version unknown: cannot tell whether the crypt key is required (only GLPI 11 needs it) and the current value is not a key",
                                 "Version de GLPI inconnue : impossible de dire si la clé est requise (seul GLPI 11 en a besoin) et la valeur actuelle n'est pas une clé",
                                 "Versión de GLPI desconocida: no se puede saber si la clave es necesaria (solo GLPI 11) y el valor actual no es una clave",
                                 "GLPI-Version unbekannt: nicht feststellbar, ob der Schlüssel nötig ist (nur GLPI 11), und der aktuelle Wert ist kein Schlüssel"),
    "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())
