#!/usr/bin/python3
# Centre KemmOS 1.25.0 — « Réparer KemmOS » depuis la clé USB (session live) : aide administrateur de
# kemmos-reparer, lancée par pkexec (action org.kemmos.centre.reparer ; dans le live, sans mot de passe).
#   reparer chercher                 systèmes KemmOS possibles (JSON) : partitions btrfs et chiffrées (LUKS)
#   reparer ouvrir <partition>       phrase de passe LUKS (si besoin) lue sur l'entrée standard, une ligne ;
#                                    sortie JSON : nom du système, instantanés, comptes
#   reparer restaurer <n>            revenir à l'instantané n (snapper rollback, comme « Restaurer et redémarrer »)
#   reparer demarrage                réinstaller le chargeur de démarrage (shim + GRUB) et refaire grub.cfg
#   reparer mesurer <compte>…        taille des dossiers personnels à copier (octets, JSON)
#   reparer copier <dossier> <compte>…   copie des dossiers personnels vers <dossier> (disque externe)
#   reparer fermer                   démonte tout, referme le disque chiffré
# Seulement depuis la session live (rd.live.image) : jamais sur un système en marche.
# Le système ouvert est monté dans /run/kemmos-reparer (/etc/fstab du système lu pour /boot, /boot/efi,
# /.snapshots, /var, /home) ; les opérations se font en chroot avec les outils du système réparé :
# snapper, kemmos-boot-sync (noyaux de /boot alignés sur le système restauré, menu GRUB des instantanés),
# shim-install et grub2-mkconfig. État entre deux appels : /run/kemmos-reparer/etat.json.
# Progression (copier, restaurer, demarrage) : lignes « ETAPE <texte> », « P <fait> <total> » ; dernière
# ligne « TERMINE » si tout s'est bien passé.
# Codes : 0 = fait, 1 = échec, 2 = usage, 3 = phrase de passe refusée, 4 = phrase de passe nécessaire,
# 5 = pas un système KemmOS, 6 = pas dans la session live.
import datetime
import json
import os
import re
import shutil
import subprocess
import sys
import xml.etree.ElementTree as ET

BASE = os.environ.get("KEMMOS_REPARER_BASE", "/run/kemmos-reparer")
HAUT = os.path.join(BASE, "haut")          # sommet du btrfs (subvolid=5) : instantanés, @home
SYS = os.path.join(BASE, "systeme")        # système (sous-volume par défaut) monté pour le chroot
ETAT = os.path.join(BASE, "etat.json")
NOM_DM = "kemmos-reparer"
TAILLE_MIN = 8 * 10**9
DESC_RETOUR = "Avant la réparation depuis la clé USB"
# pas copiés : caches, corbeille, jeux Steam (se retéléchargent), conteneurs (se recréent)
EXCLUS = {".cache", ".local/share/Trash", ".local/share/Steam/steamapps", ".local/share/containers",
          ".var/app/*/cache"}


def echec(msg, code=1):
    print(msg, file=sys.stderr, flush=True)
    sys.exit(code)


def dire(*morceaux):
    print(*morceaux, flush=True)


def lancer(cmd, **kw):
    return subprocess.run(cmd, capture_output=True, text=True, **kw)


def dans_le_live():
    if os.environ.get("KEMMOS_REPARER_TEST"):
        return True
    try:
        with open("/proc/cmdline") as f:
            return "rd.live.image" in f.read().split()
    except OSError:
        return False


# ---------- recherche ----------

def candidats(arbre):
    """Partitions (ou volumes LVM) btrfs ou LUKS assez grandes, hors clé du live (iso9660) et hors montages
    du live. arbre = sortie JSON de lsblk."""
    trouves, pile = [], [(b, None) for b in arbre]
    while pile:
        b, disque = pile.pop(0)
        if b.get("type") == "disk":
            disque = (b.get("model") or b.get("path") or "").strip()
        fs = b.get("fstype")
        monte = [p for p in b.get("mountpoints") or [] if p]
        live = any(p.startswith(("/run/initramfs", "/run/rootfsbase", "/run/overlayfs")) or p == "/" for p in monte)
        if fs in ("btrfs", "crypto_LUKS") and (b.get("size") or 0) >= TAILLE_MIN and not live:
            trouves.append({"chemin": b["path"], "taille": b["size"], "disque": disque or "",
                            "chiffre": fs == "crypto_LUKS"})
        if fs != "crypto_LUKS":   # l'enfant d'un LUKS ouvert est le même système
            pile += [(e, disque) for e in b.get("children") or []]
    return trouves


def chercher():
    r = lancer(["lsblk", "-J", "-b", "-o", "PATH,TYPE,FSTYPE,SIZE,MODEL,MOUNTPOINTS"])
    if r.returncode != 0:
        echec("lsblk : " + r.stderr.strip())
    dire(json.dumps(candidats(json.loads(r.stdout)["blockdevices"])))


# ---------- ouverture ----------

def lire_info(fichier):
    """info.xml d'un instantané snapper → dict (date en heure locale)."""
    try:
        r = ET.parse(fichier).getroot()
    except (OSError, ET.ParseError):
        return None
    g = lambda k: (r.findtext(k) or "").strip()
    try:
        d = datetime.datetime.strptime(g("date"), "%Y-%m-%d %H:%M:%S").replace(tzinfo=datetime.timezone.utc)
        date = d.astimezone().strftime("%Y-%m-%d %H:%M")
    except ValueError:
        date = ""
    important = any((u.findtext("key") or "") == "important" and (u.findtext("value") or "") == "yes"
                    for u in r.iter("userdata"))
    return {"numero": int(g("num") or 0), "type": g("type"), "date": date, "description": g("description"),
            "important": important}


def noyaux(racine):
    try:
        return sorted(v for v in os.listdir(os.path.join(racine, "usr/lib/modules"))
                      if os.path.isfile(os.path.join(racine, "usr/lib/modules", v, "vmlinuz")))
    except OSError:
        return []


def instantanes(haut, defaut):
    """Instantanés du système (sommet du btrfs monté dans haut), du plus récent au plus ancien."""
    dossier = os.path.join(haut, "@", ".snapshots")
    liste = []
    for n in os.listdir(dossier) if os.path.isdir(dossier) else []:
        if not n.isdigit() or n == "0":
            continue
        info = lire_info(os.path.join(dossier, n, "info.xml"))
        racine = os.path.join(dossier, n, "snapshot")
        if not info or not os.path.isdir(os.path.join(racine, "etc")):
            continue
        info["numero"] = int(n)
        info["actuel"] = int(n) == defaut
        info["installation"] = info["description"] == "Installation KemmOS"
        info["noyau"] = (noyaux(racine) or [""])[-1]
        liste.append(info)
    return sorted(liste, key=lambda i: -i["numero"])


def os_release(racine):
    d = {}
    try:
        with open(os.path.join(racine, "etc/os-release"), encoding="utf-8") as f:
            for ligne in f:
                if "=" in ligne:
                    k, v = ligne.rstrip("\n").split("=", 1)
                    d[k] = v.strip('"')
    except OSError:
        pass
    return d


def comptes(haut):
    """Dossiers personnels de @home (comptes du système réparé)."""
    home = os.path.join(haut, "@home")
    try:
        return sorted(c for c in os.listdir(home) if os.path.isdir(os.path.join(home, c))
                      and not c.startswith(".") and c != "lost+found")
    except OSError:
        return []


def fstab(racine):
    """Lignes utiles de /etc/fstab : [(périphérique, point, type, options)]."""
    lignes = []
    try:
        with open(os.path.join(racine, "etc/fstab"), encoding="utf-8") as f:
            for l in f:
                champs = l.split()
                if len(champs) >= 4 and not champs[0].startswith("#"):
                    lignes.append(tuple(champs[:4]))
    except OSError:
        pass
    return lignes


def peripherique(spec):
    """UUID=…, LABEL=… ou /dev/… → /dev/…"""
    if "=" in spec and not spec.startswith("/"):
        r = lancer(["blkid", "-t", spec, "-o", "device"])
        return r.stdout.split("\n")[0].strip() or None
    return spec


def monte(point):
    return lancer(["mountpoint", "-q", point]).returncode == 0


def monter(dev, point, *options):
    if not os.path.exists(point):      # point de montage d'un bind sur un fichier : le fichier existe déjà
        os.makedirs(point)
    if monte(point):
        return
    r = lancer(["mount", *options, dev, point])
    if r.returncode != 0:
        raise RuntimeError(f"mount {dev} {point} : {r.stderr.strip()}")


def defaut_snapshot(haut):
    r = lancer(["btrfs", "subvolume", "get-default", haut])
    m = re.search(r"path @/\.snapshots/(\d+)/snapshot$", r.stdout.strip())
    return int(m.group(1)) if m else None


def lire_etat():
    try:
        return json.load(open(ETAT))
    except (OSError, ValueError):
        echec("aucun système ouvert (reparer ouvrir d'abord)")


def ouvrir(chemin):
    os.makedirs(BASE, mode=0o700, exist_ok=True)
    try:
        if json.load(open(ETAT)).get("partition") != chemin:
            fermer(silencieux=True)   # un autre système était ouvert
    except (OSError, ValueError):
        pass
    r = lancer(["lsblk", "-J", "-b", "-o", "PATH,FSTYPE", chemin])
    if r.returncode != 0:
        echec(f"{chemin} : périphérique introuvable")
    fs = json.loads(r.stdout)["blockdevices"][0].get("fstype")
    dev = chemin
    if fs == "crypto_LUKS":
        mapper = "/dev/mapper/" + NOM_DM
        if not os.path.exists(mapper):
            phrase = sys.stdin.readline().rstrip("\n")
            if not phrase:
                echec("phrase de passe nécessaire", 4)
            r = subprocess.run(["cryptsetup", "open", "--type", "luks", "--key-file=-", chemin, NOM_DM],
                               input=phrase.encode(), capture_output=True)
            if r.returncode == 2:
                echec("phrase de passe refusée", 3)
            if r.returncode != 0:
                echec("cryptsetup : " + r.stderr.decode(errors="replace").strip())
        dev = mapper
        if lancer(["lsblk", "-no", "FSTYPE", mapper]).stdout.strip() != "btrfs":
            fermer(silencieux=True)
            echec("disposition non prise en charge : le disque chiffré ne contient pas directement un btrfs", 5)
    try:
        monter(dev, HAUT, "-o", "subvolid=5")
    except RuntimeError as e:
        echec(str(e))
    defaut = defaut_snapshot(HAUT)
    racine = os.path.join(HAUT, "@", ".snapshots", str(defaut), "snapshot") if defaut else os.path.join(HAUT, "@")
    rel = os_release(racine)
    if not os.path.isdir(os.path.join(HAUT, "@", ".snapshots")) or not re.search(
            r"kemmos|geekos", rel.get("NAME", "") + rel.get("ID", ""), re.I):
        fermer(silencieux=True)
        echec("pas un système KemmOS", 5)
    json.dump({"partition": chemin, "dev": dev, "defaut": defaut}, open(ETAT, "w"))
    dire(json.dumps({"nom": rel.get("PRETTY_NAME") or rel.get("NAME", "KemmOS"), "defaut": defaut,
                     "instantanes": instantanes(HAUT, defaut), "comptes": comptes(HAUT),
                     "efi": os.path.isdir("/sys/firmware/efi")}))


# ---------- système monté pour le chroot ----------

def monter_systeme(etat):
    """Monte le système par défaut dans SYS avec /boot, /boot/efi, /.snapshots, /var et les systèmes de
    fichiers du noyau, comme pour un démarrage normal. Renvoie la liste des points montés."""
    monter(etat["dev"], SYS)
    # dans l'ordre des dossiers : /boot avant /boot/efi, quel que soit l'ordre des lignes de fstab
    for spec, point, typ, opts in sorted(fstab(SYS), key=lambda l: l[1].count("/") if l[1] != "/" else 0):
        if point in ("/.snapshots", "/var", "/boot", "/boot/efi"):
            dev = etat["dev"] if typ == "btrfs" else peripherique(spec)
            if not dev:
                raise RuntimeError(f"{point} : {spec} introuvable")
            options = [o for o in opts.split(",") if o.startswith("subvol")] if typ == "btrfs" else []
            monter(dev, SYS + point, *(["-o", ",".join(options)] if options else []))
    for src, point, opts in (("proc", "/proc", ["-t", "proc"]), ("sysfs", "/sys", ["-t", "sysfs"]),
                             ("/dev", "/dev", ["--rbind"]), ("tmpfs", "/run", ["-t", "tmpfs"])):
        monter(src, SYS + point, *opts)
    if os.path.isdir("/sys/firmware/efi/efivars") and os.path.isdir(SYS + "/sys/firmware/efi/efivars"):
        monter("efivarfs", SYS + "/sys/firmware/efi/efivars", "-t", "efivarfs")


def chroot(*cmd):
    return lancer(["chroot", SYS, *cmd])


def demonter_systeme():
    if os.path.isdir(SYS):
        lancer(["umount", "-R", SYS])
        if monte(SYS):
            lancer(["umount", "-R", "-l", SYS])


def restaurer(n):
    etat = lire_etat()
    racine = os.path.join(HAUT, "@", ".snapshots", str(n), "snapshot")
    if not os.path.isdir(os.path.join(racine, "etc")):
        echec(f"instantané {n} introuvable")
    if n == etat.get("defaut"):
        echec(f"l'instantané {n} est déjà le système actuel")
    try:
        dire("ETAPE monter")
        monter_systeme(etat)
        # Le plugin snapper 50-kemmos-boot attend kemmos-boot-sync.service, qui ne tourne pas en chroot :
        # neutralisé le temps du rollback, puis kemmos-boot-sync lancé directement.
        plugin = SYS + "/usr/lib/snapper/plugins/50-kemmos-boot"
        neutre = os.path.exists(plugin)
        if neutre:
            monter(SYS + "/usr/bin/true", plugin, "--bind")
        dire("ETAPE instantane")
        r = chroot("snapper", "--no-dbus", "--ambit", "classic", "rollback", "-d", DESC_RETOUR, str(n))
        if neutre:
            lancer(["umount", plugin])
        if r.returncode != 0:
            raise RuntimeError("snapper : " + (r.stderr or r.stdout).strip())
        nouveau = defaut_snapshot(HAUT)
        if not nouveau or nouveau == etat.get("defaut"):
            raise RuntimeError("le système par défaut n'a pas changé : " + r.stdout.strip())
        chroot("snapper", "--no-dbus", "modify", "-d", f"Restauré depuis la clé USB (instantané {n})", str(nouveau))
        # /boot et GRUB alignés avec les outils du système restauré (le système actuel est peut-être cassé) :
        # remonté, la racine est maintenant le nouveau sous-volume par défaut
        demonter_systeme()
        monter_systeme(etat)
        dire("ETAPE demarrage")
        if os.path.exists(SYS + "/usr/sbin/kemmos-boot-sync"):
            r = chroot("/usr/sbin/kemmos-boot-sync", "rollback-post")
            if r.returncode != 0:
                raise RuntimeError("kemmos-boot-sync : " + (r.stderr or r.stdout).strip())
        if os.path.exists(SYS + "/usr/libexec/kemmos-update/retour-auto"):
            chroot("/usr/libexec/kemmos-update/retour-auto", "desarmer")
        # fichiers écrits depuis le live : tout le système est réétiqueté au démarrage suivant (SELinux)
        cible = os.path.join(HAUT, "@", ".snapshots", str(nouveau), "snapshot")
        if os.path.isdir(os.path.join(cible, "etc/selinux")):
            open(os.path.join(cible, "etc/selinux/.autorelabel"), "w").close()
        etat["defaut"] = nouveau
        json.dump(etat, open(ETAT, "w"))
    except (RuntimeError, OSError) as e:
        demonter_systeme()
        echec(str(e))
    demonter_systeme()
    lancer(["sync"])
    dire("TERMINE")


def demarrage():
    etat = lire_etat()
    try:
        dire("ETAPE monter")
        monter_systeme(etat)
        if not monte(SYS + "/boot"):
            raise RuntimeError("/boot introuvable dans le système")
        if os.path.isdir("/sys/firmware/efi"):
            if not monte(SYS + "/boot/efi"):
                raise RuntimeError("partition EFI (/boot/efi) introuvable dans le système")
            dire("ETAPE chargeur")
            # comme l'installateur (shellprocess-secureboot.conf) : shim signé + grub.efi signé, entrée UEFI
            r = chroot("shim-install", "--config-file=/boot/grub2/grub.cfg", "--bootloader-id=KemmOS")
            if r.returncode != 0:
                raise RuntimeError("shim-install : " + (r.stderr or r.stdout).strip()[-600:])
        else:
            disque = lancer(["lsblk", "-no", "PKNAME", etat["partition"]]).stdout.split("\n")[0].strip()
            if not disque:
                raise RuntimeError("disque du système introuvable")
            dire("ETAPE chargeur")
            r = chroot("grub2-install", "/dev/" + disque)
            if r.returncode != 0:
                raise RuntimeError("grub2-install : " + (r.stderr or r.stdout).strip()[-600:])
        dire("ETAPE menu")
        r = chroot("grub2-mkconfig", "-o", "/boot/grub2/grub.cfg")
        if r.returncode != 0:
            raise RuntimeError("grub2-mkconfig : " + (r.stderr or r.stdout).strip()[-600:])
        if os.path.exists(SYS + "/usr/sbin/kemmos-boot-sync"):
            chroot("/usr/sbin/kemmos-boot-sync", "boot")
    except (RuntimeError, OSError) as e:
        demonter_systeme()
        echec(str(e))
    demonter_systeme()
    lancer(["sync"])
    dire("TERMINE")


# ---------- copie des dossiers personnels ----------

def exclu(rel):
    """Chemin relatif au dossier personnel à ne pas copier."""
    for motif in EXCLUS:
        if "*" in motif:
            debut, fin = motif.split("*", 1)
            if rel.startswith(debut) and rel.endswith(fin) and rel.count("/") == motif.count("/"):
                return True
        elif rel == motif:
            return True
    return False


def parcourir(dossier):
    """(chemin complet, chemin relatif, taille) des fichiers et liens à copier."""
    for racine, dossiers, fichiers in os.walk(dossier):
        rel_racine = os.path.relpath(racine, dossier)
        rel_racine = "" if rel_racine == "." else rel_racine + "/"
        dossiers[:] = [d for d in dossiers if not exclu(rel_racine + d)
                       and not os.path.islink(os.path.join(racine, d))]
        for d in os.listdir(racine):
            p = os.path.join(racine, d)
            if os.path.islink(p) and os.path.isdir(p):
                yield p, rel_racine + d, 0
        for f in fichiers:
            p = os.path.join(racine, f)
            try:
                st = os.lstat(p)
            except OSError:
                continue
            if os.path.islink(p) or os.path.isfile(p):
                yield p, rel_racine + f, st.st_size if not os.path.islink(p) else 0


def mesurer(liste):
    home = os.path.join(HAUT, "@home")
    lire_etat()
    dire(json.dumps({c: sum(t for _p, _r, t in parcourir(os.path.join(home, c))) for c in liste
                     if os.path.isdir(os.path.join(home, c))}))


def copier(dest, liste):
    lire_etat()
    home = os.path.join(HAUT, "@home")
    if not os.path.isdir(dest) or not dest.startswith("/run/media/"):
        echec("destination refusée : seulement un disque externe (/run/media/…)")
    uid = int(os.environ.get("PKEXEC_UID", "0") or 0)
    gid = 100
    try:
        import pwd
        gid = pwd.getpwuid(uid).pw_gid
    except (KeyError, ImportError):
        pass
    fichiers = [(c, p, r, t) for c in liste for p, r, t in parcourir(os.path.join(home, c))]
    total = sum(t for *_x, t in fichiers)
    st = os.statvfs(dest)
    if total > st.f_bavail * st.f_frsize:
        echec("place insuffisante sur le disque externe")
    base = os.path.join(dest, "KemmOS-copie-" + datetime.datetime.now().strftime("%Y-%m-%d-%H%M"))
    os.makedirs(base, exist_ok=True)
    fait, echecs, dernier = 0, 0, -1
    dire("P", 0, total)
    for compte, p, rel, t in fichiers:
        cible = os.path.join(base, compte, rel)
        try:
            os.makedirs(os.path.dirname(cible), exist_ok=True)
            if os.path.islink(p):
                os.symlink(os.readlink(p), cible)
            else:
                shutil.copy2(p, cible)
        except OSError:
            echecs += 1   # lien sur un disque FAT, nom de fichier refusé…
        fait += t
        pourcent = int(fait * 100 / total) if total else 100
        if pourcent != dernier:
            dernier = pourcent
            dire("P", fait, total)
    # fichiers au nom de l'utilisateur du live (disque ext4 ; sans effet sur FAT, exFAT, NTFS)
    if uid:
        try:
            for racine, dossiers, noms in os.walk(base):
                for x in [racine] + [os.path.join(racine, n) for n in noms]:
                    os.lchown(x, uid, gid)
        except OSError:
            pass
    lancer(["sync"])
    dire("ECHECS", echecs)
    dire("DOSSIER", base)
    dire("TERMINE")


# ---------- fermeture ----------

def fermer(silencieux=False):
    demonter_systeme()
    if monte(HAUT):
        lancer(["umount", HAUT])
    if os.path.exists("/dev/mapper/" + NOM_DM):
        lancer(["cryptsetup", "close", NOM_DM])
    try:
        os.remove(ETAT)
    except OSError:
        pass
    if not silencieux:
        dire("TERMINE")


def main(a):
    if os.geteuid() != 0 and not os.environ.get("KEMMOS_REPARER_TEST"):
        echec("droits administrateur nécessaires")
    if not dans_le_live():
        echec("Réparer KemmOS ne s'utilise que depuis la clé USB KemmOS (session live)", 6)
    if a == ["chercher"]:
        chercher()
    elif len(a) == 2 and a[0] == "ouvrir" and a[1].startswith("/dev/"):
        ouvrir(a[1])
    elif len(a) == 2 and a[0] == "restaurer" and a[1].isdigit():
        restaurer(int(a[1]))
    elif a == ["demarrage"]:
        demarrage()
    elif len(a) >= 2 and a[0] == "mesurer" and all(re.fullmatch(r"[\w.-]+", c) for c in a[1:]):
        mesurer(a[1:])
    elif len(a) >= 3 and a[0] == "copier" and all(re.fullmatch(r"[\w.-]+", c) for c in a[2:]):
        copier(os.path.realpath(a[1]), a[2:])
    elif a == ["fermer"]:
        fermer()
    else:
        print(__doc__ or "usage : voir l'en-tête de /usr/libexec/kemmos-centre/reparer", file=sys.stderr)
        sys.exit(2)


if __name__ == "__main__":
    main(sys.argv[1:])
