#!/usr/bin/python3
"""Assistant root de l'annuaire d'entreprise d'AuxiNux (lancé par pkexec depuis les Paramètres) :
  auxinux-directory install ad|ldap         installe les composants manquants (auxi, sinon apt-get)
  auxinux-directory join-ad DOMAINE ADMIN   rejoint un domaine Active Directory (mot de passe sur l'entrée)
  auxinux-directory join-ldap               relie le PC à un serveur OpenLDAP (réglages JSON sur l'entrée)
  auxinux-directory leave                   quitte l'annuaire (comptes locaux seulement)
Réservé à l'édition activée : l'assistant le revérifie lui-même."""
import datetime
import json
import os
import shutil
import subprocess
import sys

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

ROOT = os.environ.get("AUXINUX_DIRECTORY_ROOT", "/")   # tests : arborescence de remplacement
SSSD_CONF = os.path.join(ROOT, "etc/sssd/sssd.conf")
NSSWITCH = os.path.join(ROOT, "etc/nsswitch.conf")
BACKUP = ".auxinux-backup"


def run(argv, stdin=None):
    result = subprocess.run(argv, input=stdin, capture_output=True, text=True,
                            env=dict(os.environ, DEBIAN_FRONTEND="noninteractive", LC_ALL="C.UTF-8",
                                     # paquets du système : auxi les installe même si DEB est désactivé
                                     AUXI_DEB_SYSTEME="1"))
    output = (result.stdout + result.stderr).strip()
    if result.returncode != 0:
        raise RuntimeError(output.splitlines()[-1] if output else f"{argv[0]} : code {result.returncode}")
    return output


def fail(message, code=1):
    print(message)
    return code


def save_state(kind, name, extra=None):
    data = {"type": kind, "name": name,
            "joined": datetime.datetime.now().astimezone().isoformat(timespec="seconds"), **(extra or {})}
    target = directory.STATE_FILE
    target.parent.mkdir(parents=True, exist_ok=True)
    tmp = target.with_name(".directory.tmp")
    tmp.write_text(json.dumps(data, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
    os.chmod(tmp, 0o644)
    os.replace(tmp, target)


def backup(path):
    if os.path.exists(path) and not os.path.exists(path + BACKUP):
        shutil.copy2(path, path + BACKUP)


def install(kind):
    missing = directory.missing_packages(kind)
    if not missing:
        print("Composants déjà installés.")
        return 0
    auxi = shutil.which("auxi")
    argv = [auxi, "--yes", "install", "--deb", *missing] if auxi else ["apt-get", "install", "-y", *missing]
    try:
        run(argv)
    except RuntimeError as e:
        return fail(f"Installation impossible : {e}")
    print("Composants installés.")
    return 0


def join_ad(domain, user, password):
    if not directory.valid_domain(domain):
        return fail("Nom de domaine invalide.", 2)
    if directory.missing_packages("ad"):
        return fail("Composants manquants : " + ", ".join(directory.missing_packages("ad")), 3)
    try:
        run(["realm", "join", "--verbose", f"--user={user}", domain], stdin=password + "\n")
        run(["pam-auth-update", "--enable", "mkhomedir"])
    except RuntimeError as e:
        return fail(f"Le domaine n'a pas pu être rejoint : {e}")
    save_state("ad", domain.lower(), {"admin": user})
    print(f"Relié au domaine {domain}.")
    return 0


def join_ldap(settings):
    uri, base = settings.get("uri", ""), settings.get("base", "")
    if not directory.valid_uri(uri):
        return fail("Adresse du serveur invalide (ldap://… ou ldaps://…).", 2)
    if not directory.valid_base(base):
        return fail("Base de recherche invalide (ex. dc=exemple,dc=org).", 2)
    if ROOT == "/" and directory.missing_packages("ldap"):
        return fail("Composants manquants : " + ", ".join(directory.missing_packages("ldap")), 3)
    conf = directory.sssd_ldap_conf(uri, base, settings.get("starttls", True), settings.get("verify", True),
                                     settings.get("bind_dn") or None, settings.get("bind_password") or None)
    try:
        os.makedirs(os.path.dirname(SSSD_CONF), exist_ok=True)
        backup(SSSD_CONF)
        with open(SSSD_CONF, "w", encoding="utf-8") as f:
            f.write(conf)
        os.chmod(SSSD_CONF, 0o600)   # sssd refuse une configuration lisible par d'autres
        if os.path.exists(NSSWITCH):
            backup(NSSWITCH)
            with open(NSSWITCH, encoding="utf-8") as f:
                text = f.read()
            with open(NSSWITCH, "w", encoding="utf-8") as f:
                f.write(directory.nsswitch_with_sss(text))
        if ROOT == "/":
            run(["pam-auth-update", "--enable", "sss", "mkhomedir"])
            run(["systemctl", "enable", "sssd"])
            run(["systemctl", "restart", "sssd"])
    except (OSError, RuntimeError) as e:
        return fail(f"Le serveur n'a pas pu être configuré : {e}")
    save_state("ldap", uri, {"base": base})
    print(f"Relié au serveur {uri}.")
    return 0


def leave():
    current = directory.state()
    if current is None:
        print("Aucun annuaire.")
        return 0
    try:
        if current["type"] == "ad" and ROOT == "/":
            run(["realm", "leave", current["name"]])
        elif current["type"] == "ldap":
            if os.path.exists(SSSD_CONF + BACKUP):
                os.replace(SSSD_CONF + BACKUP, SSSD_CONF)
            elif os.path.exists(SSSD_CONF):
                os.remove(SSSD_CONF)
            if ROOT == "/":
                subprocess.run(["systemctl", "restart", "sssd"], capture_output=True)
    except (OSError, RuntimeError) as e:
        return fail(f"L'annuaire n'a pas pu être quitté : {e}")
    directory.STATE_FILE.unlink(missing_ok=True)
    print("Annuaire quitté.")
    return 0


def main(argv):
    if not activation.has("ldap"):
        return fail("L'annuaire d'entreprise demande l'activation d'AuxiNux OS.", 4)
    if len(argv) == 3 and argv[1] == "install" and argv[2] in directory.PACKAGES:
        return install(argv[2])
    if len(argv) == 4 and argv[1] == "join-ad":
        return join_ad(argv[2], argv[3], sys.stdin.readline().rstrip("\n"))
    if len(argv) == 2 and argv[1] == "join-ldap":
        try:
            settings = json.loads(sys.stdin.read() or "{}")
        except ValueError:
            return fail("Réglages illisibles.", 2)
        return join_ldap(settings)
    if len(argv) == 2 and argv[1] == "leave":
        return leave()
    print(__doc__)
    return 64


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