#!/usr/bin/python3
# KemmOS : corrige le lanceur de certains Flatpaks, à chaque ouverture de session (autostart).
# FreeTube déclare StartupNotify=true sans jamais envoyer le signal de fin de démarrage : lancé depuis le
# dock ou la grille, GNOME garde le pointeur « occupé » une vingtaine de secondes (vu sur PC réel, 22 oct.
# 2026 ; « flatpak run » direct démarre aussitôt). Copie du lanceur exporté dans ~/.local/share/applications
# (avant les exports Flatpak dans la recherche XDG, contrairement à /usr/local/share) avec
# StartupNotify=false. Refaite à chaque session : suit les mises à jour du Flatpak ; TryExec cache la copie
# dès que le Flatpak est désinstallé, elle est retirée à la session suivante. Une copie faite à la main par
# l'utilisateur (sans la marque X-KemmOS-Lanceur) n'est jamais touchée.
# 1.13.0 : une seule fois par compte, KemmOS Fichiers prend la place de Nautilus dans le dock et pour ouvrir les
# dossiers (PC installés avant l'ISO 1.6) ; ensuite l'interrupteur de KemmOS Style › Dock décide.
import os
import sys

APPLIS = ["io.freetubeapp.FreeTube"]
MARQUE = "X-KemmOS-Lanceur=StartupNotify"

maison = os.path.expanduser("~")
donnees = os.environ.get("XDG_DATA_HOME") or os.path.join(maison, ".local/share")
cible_dir = os.path.join(donnees, "applications")
installations = [os.path.join(donnees, "flatpak/exports"), "/var/lib/flatpak/exports"]


def corrige(texte, binaire):
    """Lanceur corrigé, ou None s'il n'y a rien à corriger."""
    lignes, section, change = [], None, False
    for l in texte.splitlines():
        s = l.strip()
        if s.startswith("[") and s.endswith("]"):
            section = s
            lignes.append(l)
            if s == "[Desktop Entry]":
                lignes += [MARQUE, "TryExec=" + binaire]
            continue
        if section == "[Desktop Entry]":
            if s.startswith("TryExec="):
                continue
            if s.replace(" ", "") == "StartupNotify=true":
                lignes.append("StartupNotify=false")
                change = True
                continue
        lignes.append(l)
    return "\n".join(lignes) + "\n" if change else None


def traite(app):
    cible = os.path.join(cible_dir, app + ".desktop")
    actuel = None
    if os.path.lexists(cible):
        try:
            with open(cible, encoding="utf-8") as f:
                actuel = f.read()
        except OSError:
            return
        if MARQUE not in actuel.splitlines():
            return
    nouveau = None
    for inst in installations:
        source = os.path.join(inst, "share/applications", app + ".desktop")
        if os.path.exists(source):
            with open(source, encoding="utf-8") as f:
                nouveau = corrige(f.read(), os.path.join(inst, "bin", app))
            break
    if nouveau is None:
        if actuel is not None:
            os.remove(cible)
        return
    if nouveau == actuel:
        return
    os.makedirs(cible_dir, exist_ok=True)
    tmp = cible + ".kemmos-tmp"
    with open(tmp, "w", encoding="utf-8") as f:
        f.write(nouveau)
    os.replace(tmp, cible)


FICHIERS = "org.kemmos.Fichiers.desktop"
NAUTILUS = "org.gnome.Nautilus.desktop"
config = os.environ.get("XDG_CONFIG_HOME") or os.path.join(maison, ".config")
MARQUE_FICHIERS = os.path.join(config, "kemmos-style", "fichiers-a-la-place-de-nautilus")


def dock_sans_nautilus(favoris):
    """Les favoris du dock avec KemmOS Fichiers à la place de Nautilus (rien d'ajouté si Nautilus n'y est pas :
    il a été retiré exprès)."""
    if NAUTILUS not in favoris:
        return favoris
    res = []
    for f in favoris:
        f = FICHIERS if f == NAUTILUS else f
        if f not in res:
            res.append(f)
    return res


def fichiers_une_fois():
    if os.path.exists(MARQUE_FICHIERS) or not os.path.exists("/usr/share/applications/" + FICHIERS):
        return
    from gi.repository import Gio
    try:
        import gi
        gi.require_version("GioUnix", "2.0")
        from gi.repository.GioUnix import DesktopAppInfo
    except (ValueError, ImportError):
        DesktopAppInfo = Gio.DesktopAppInfo
    shell = Gio.Settings.new("org.gnome.shell")
    favoris = shell.get_strv("favorite-apps")
    nouveaux = dock_sans_nautilus(favoris)
    if nouveaux != favoris:
        shell.set_strv("favorite-apps", nouveaux)
        Gio.Settings.sync()
    actuel = Gio.AppInfo.get_default_for_type("inode/directory", False)
    if actuel is None or actuel.get_id() == NAUTILUS:
        DesktopAppInfo.new(FICHIERS).set_as_default_for_type("inode/directory")
    os.makedirs(os.path.dirname(MARQUE_FICHIERS), exist_ok=True)
    open(MARQUE_FICHIERS, "w").close()


if __name__ == "__main__":
    for app in APPLIS:
        try:
            traite(app)
        except Exception as e:
            print("kemmos-lanceurs :", app, ":", e, file=sys.stderr)
    try:
        fichiers_une_fois()
    except Exception as e:
        print("kemmos-lanceurs : KemmOS Fichiers :", e, file=sys.stderr)
