#!/usr/bin/python3
"""Antivirus ClamAV depuis les Paramètres et l'application Antivirus (root par pkexec, mot de passe de
l'administrateur). Les lignes affichées sont reprises par l'interface au fil de l'eau.
  auxinux-antivirus enable         installe ClamAV au besoin, télécharge les signatures et active leur mise à jour
  auxinux-antivirus disable        arrête la mise à jour automatique et le service d'analyse (ClamAV reste installé)
  auxinux-antivirus update         met à jour les signatures maintenant (freshclam)
  auxinux-antivirus daemon on|off  service d'analyse rapide (clamd, environ 1 Go de mémoire)
  auxinux-antivirus shield on|off  AuxiNuxOS Shield : protection en temps réel (clamonacc), vérifiée par EICAR
  auxinux-antivirus shield paths DOSSIER…   dossiers surveillés par AuxiNuxOS Shield
  auxinux-antivirus shield verify  refait la vérification réelle du blocage"""
import json
import os
import shutil
import subprocess
import sys
import time

sys.path.insert(0, os.environ.get("AUXINUX_SHELL_PYTHON", "/usr/share/auxinux-shell/python"))
from auxinux_shell.services import activation, shield  # noqa: E402

# AUXI_DEB_SYSTEME=1 : paquets du système installés par auxi même si l'installation DEB des applications est
# désactivée (réglage « deb » d'AuxiNux OS), sans modifier ce réglage — comme l'assistant de premier démarrage.
ENV = {"PATH": os.environ.get("AUXINUX_ANTIVIRUS_PATH", "/usr/sbin:/usr/bin:/sbin:/bin"),   # variable : tests
       "LC_ALL": "C.UTF-8", "DEBIAN_FRONTEND": "noninteractive", "HOME": "/root", "AUXI_DEB_SYSTEME": "1"}
BASE = ["clamav", "clamav-freshclam"]
DAEMON = ["clamav-daemon", "clamdscan"]
UPDATER_UNIT = "clamav-freshclam.service"
DAEMON_UNITS = ["clamav-daemon.service", "clamav-daemon.socket"]
DB_DIR = os.environ.get("AUXINUX_CLAMAV_DB", "/var/lib/clamav")   # variable : tests
SHIELD_UNIT = shield.SERVICE
DEBIAN_ONACCESS_UNIT = "clamav-clamonacc.service"   # celui du paquet : AuxiNuxOS Shield le remplace
SHIELD_WAIT = int(os.environ.get("AUXINUX_SHIELD_WAIT", "240"))


def say(text):
    print(text, flush=True)


LAST = {"line": ""}   # dernière ligne d'une commande : la raison d'un échec, montrée à l'utilisateur


def stream(argv):
    """Lance une commande en relayant sa sortie ligne par ligne ; renvoie son code."""
    try:
        process = subprocess.Popen(argv, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, env=ENV)
    except OSError as e:
        say(str(e))
        LAST["line"] = str(e)
        return 127
    for line in process.stdout:
        if line.strip():
            say(line.rstrip())
            LAST["line"] = line.strip()
    return process.wait()


def quiet(argv):
    return subprocess.run(argv, capture_output=True, text=True, env=ENV).returncode


def missing(packages):
    result = subprocess.run(["dpkg-query", "-W", "-f=${Package} ${db:Status-Status}\n", *packages],
                            capture_output=True, text=True, env=ENV)
    present = {line.split()[0] for line in result.stdout.splitlines() if line.endswith(" installed")}
    return [p for p in packages if p not in present]


def install(packages):
    todo = missing(packages)
    if not todo:
        return 0
    say("Installation de " + ", ".join(todo) + "…")
    # AuxiNux OS : auxi (apt-get y est remplacé par un message) ; ailleurs : apt-get.
    auxi = shutil.which("auxi", path=ENV["PATH"])
    argv = [auxi, "--yes", "install", "--deb", *todo] if auxi else ["apt-get", "install", "-y", *todo]
    if stream(argv) == 0:
        return 0
    say("Actualisation des listes de paquets…")   # listes trop vieilles : on les rafraîchit une fois
    stream([auxi, "--yes", "update", "--deb"] if auxi else ["apt-get", "update"])
    if stream(argv) == 0:
        return 0
    say(f"Installation impossible : {LAST['line']}" if LAST["line"] else "Installation impossible.")
    return 1


def has_signatures():
    return any(os.path.exists(os.path.join(DB_DIR, f"daily{s}")) for s in (".cvd", ".cld"))


def update():
    if not shutil.which("freshclam", path=ENV["PATH"]):
        say("ClamAV n'est pas installé.")
        return 1
    was_active = quiet(["systemctl", "is-active", "--quiet", UPDATER_UNIT]) == 0
    if was_active:   # le service tient le verrou de freshclam : on l'arrête le temps de la mise à jour
        quiet(["systemctl", "stop", UPDATER_UNIT])
    say("Mise à jour des signatures…")
    code = stream(["freshclam", "--stdout"])
    if was_active:
        quiet(["systemctl", "start", UPDATER_UNIT])
    if code != 0:
        say("Mise à jour des signatures impossible.")
        return 1
    if quiet(["systemctl", "is-active", "--quiet", DAEMON_UNITS[0]]) == 0:
        quiet(["systemctl", "reload-or-restart", DAEMON_UNITS[0]])
    say("Signatures à jour.")
    return 0


def enable():
    if install(BASE) != 0:
        return 1
    # Le paquet du service d'analyse s'active tout seul à l'installation : il reste au choix de l'utilisateur.
    if not has_signatures():
        say("Premier téléchargement des signatures (environ 200 Mo)…")
        quiet(["systemctl", "stop", UPDATER_UNIT])
        if stream(["freshclam", "--stdout"]) != 0 and not has_signatures():
            say("Téléchargement des signatures impossible : vérifiez la connexion à Internet.")
            return 1
    if quiet(["systemctl", "enable", "--now", UPDATER_UNIT]) != 0:
        say("Le service de mise à jour des signatures n'a pas démarré.")
        return 1
    say("Antivirus activé.")
    return 0


def disable():
    shield_off(quietly=True)
    quiet(["systemctl", "disable", "--now", UPDATER_UNIT])
    quiet(["systemctl", "disable", "--now", *DAEMON_UNITS])
    say("Antivirus désactivé.")
    return 0


def daemon(on):
    if not on:
        if shield_enabled():
            say("AuxiNuxOS Shield utilise le service d'analyse : désactivez d'abord la protection en temps réel.")
            return 1
        quiet(["systemctl", "disable", "--now", *DAEMON_UNITS])
        say("Service d'analyse arrêté.")
        return 0
    if install(BASE + DAEMON) != 0:
        return 1
    if not has_signatures() and update() != 0:
        return 1
    if quiet(["systemctl", "enable", "--now", DAEMON_UNITS[0]]) != 0:
        say("Le service d'analyse n'a pas démarré.")
        return 1
    say("Service d'analyse démarré.")
    return 0


# ---------- AuxiNuxOS Shield ----------

def shield_enabled():
    return quiet(["systemctl", "is-enabled", "--quiet", SHIELD_UNIT]) == 0


def write_shield_config(paths):
    """Enregistre les dossiers surveillés et régénère la configuration de clamonacc."""
    shield.CONF_DIR.mkdir(parents=True, exist_ok=True)
    tmp = shield.CONF_FILE.with_name(".shield.json.tmp")
    tmp.write_text(json.dumps({"paths": paths}, ensure_ascii=False, indent=1) + "\n", encoding="utf-8")
    os.chmod(tmp, 0o644)
    os.replace(tmp, shield.CONF_FILE)
    text = shield.clamonacc_conf(paths, shield.excludes_for(paths), shield.clamd_socket())
    tmp = shield.CLAMONACC_CONF.with_name(".shield-clamonacc.conf.tmp")
    tmp.write_text(text, encoding="utf-8")
    os.chmod(tmp, 0o644)
    os.replace(tmp, shield.CLAMONACC_CONF)


def main_pid(unit):
    result = subprocess.run(["systemctl", "show", "-p", "MainPID", "--value", unit], capture_output=True,
                            text=True, env=ENV)
    value = result.stdout.strip()
    return int(value) if value.isdigit() else 0


def wait_verified(since):
    """Attend la vérification réelle par le service (status.json écrit par le service lui-même)."""
    say("Vérification du blocage avec le fichier de test EICAR…")
    deadline = time.monotonic() + SHIELD_WAIT
    while time.monotonic() < deadline:
        status = shield.read_status() or {}
        pid = main_pid(SHIELD_UNIT)
        if status.get("pid") == pid and pid and status.get("time", "") >= since:
            if status.get("state") == "protected":
                say("Protection en temps réel vérifiée : les fichiers infectés sont bloqués.")
                return 0
            if status.get("state") in ("error", "unentitled"):
                say("Protection en temps réel en erreur : " + (status.get("error") or "?"))
                return 1
        if pid == 0 and quiet(["systemctl", "is-failed", "--quiet", SHIELD_UNIT]) == 0:
            say("Le service AuxiNuxOS Shield s'est arrêté : " + ((shield.read_status() or {}).get("error") or
                                                                  "voir journalctl -u " + SHIELD_UNIT))
            return 1
        time.sleep(1)
    say("La vérification n'a pas abouti à temps : la protection n'est pas confirmée.")
    return 1


def shield_on():
    if not activation.entitled("shield"):
        say("AuxiNuxOS Shield fait partie du mode PRO.")
        return 1
    if install(BASE + DAEMON) != 0:
        return 1
    if not has_signatures() and update() != 0:
        return 1
    quiet(["systemctl", "enable", "--now", UPDATER_UNIT])
    say("Démarrage du service d'analyse (clamd)…")
    if quiet(["systemctl", "enable", "--now", *DAEMON_UNITS]) != 0:
        say("Le service d'analyse (clamd) n'a pas démarré.")
        return 1
    if quiet(["systemctl", "is-enabled", "--quiet", DEBIAN_ONACCESS_UNIT]) == 0 or \
            quiet(["systemctl", "is-active", "--quiet", DEBIAN_ONACCESS_UNIT]) == 0:
        quiet(["systemctl", "disable", "--now", DEBIAN_ONACCESS_UNIT])
    write_shield_config(shield.load_config()["paths"])
    since = shield.now_iso()
    quiet(["systemctl", "enable", SHIELD_UNIT])
    if quiet(["systemctl", "restart", SHIELD_UNIT]) != 0:
        say("Le service AuxiNuxOS Shield n'a pas démarré.")
        return 1
    return wait_verified(since)


def shield_off(quietly=False):
    quiet(["systemctl", "disable", "--now", SHIELD_UNIT])
    try:
        shield.write_status("stopped", verified=None, error=None, pid=None)
    except OSError:
        pass
    if not quietly:
        say("Protection en temps réel désactivée ; ClamAV et les analyses manuelles restent disponibles.")
    return 0


def shield_paths(paths):
    try:
        clean = []
        for path in paths:
            real = shield.validate_path(path)
            if real not in clean:
                clean.append(real)
    except ValueError as e:
        say(str(e))
        return 2
    if not clean:
        say("Choisissez au moins un dossier.")
        return 2
    write_shield_config(clean)
    say("Dossiers surveillés : " + ", ".join(clean))
    if shield_enabled():
        since = shield.now_iso()
        quiet(["systemctl", "restart", SHIELD_UNIT])
        return wait_verified(since)
    return 0


def shield_verify():
    if quiet(["systemctl", "is-active", "--quiet", SHIELD_UNIT]) != 0:
        say("AuxiNuxOS Shield n'est pas en marche.")
        return 1
    since = shield.now_iso()
    time.sleep(1)       # horodatage à la seconde : le nouvel état sera plus récent
    quiet(["systemctl", "kill", "--signal=SIGUSR1", "--kill-whom=main", SHIELD_UNIT])
    return wait_verified(since)


def main(argv):
    args = argv[1:]
    if args in (["shield", "on"], ["shield", "off"]):
        return shield_on() if args[1] == "on" else shield_off()
    if len(args) >= 3 and args[:2] == ["shield", "paths"]:
        return shield_paths(args[2:])
    if args == ["shield", "verify"]:
        return shield_verify()
    if args == ["enable"]:
        return enable()
    if args == ["disable"]:
        return disable()
    if args == ["update"]:
        return update()
    if len(args) == 2 and args[0] == "daemon" and args[1] in ("on", "off"):
        return daemon(args[1] == "on")
    print(__doc__)
    return 64


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