#!/usr/bin/env python3
from pathlib import Path
import os
import shutil
import xml.etree.ElementTree as ET

home = Path.home()
config = home / ".config" / "labwc" / "rc.xml"
config.parent.mkdir(parents=True, exist_ok=True)

if config.exists():
    backup = config.with_suffix(".xml.salsabil-backup")
    if not backup.exists():
        shutil.copy2(config, backup)
    tree = ET.parse(config)
    root = tree.getroot()
else:
    root = ET.Element("openbox_config")
    tree = ET.ElementTree(root)

ns = ""
if root.tag.startswith("{"):
    ns = root.tag.split("}")[0] + "}"
keyboard = root.find(f"{ns}keyboard")
if keyboard is None:
    keyboard = ET.SubElement(root, f"{ns}keyboard")

def ensure_keybind(key: str, command: str):
    for kb in keyboard.findall(f"{ns}keybind"):
        if kb.get("key") == key:
            keyboard.remove(kb)
    kb = ET.SubElement(keyboard, f"{ns}keybind", {"key": key})
    action = ET.SubElement(kb, f"{ns}action", {"name": "Execute"})
    cmd = ET.SubElement(action, f"{ns}command")
    cmd.text = command

ensure_keybind("C-A-r", "/opt/salsabil-tv/bin/reload-player.sh")
ensure_keybind("C-A-w", "/opt/salsabil-tv/bin/open-network-settings.sh")
ET.indent(tree, space="  ")
tree.write(config, encoding="utf-8", xml_declaration=True)
print(f"Raccourcis labwc configurés dans {config}")
