#!/bin/bash
# Mundo Games Toolbox - sistema propio "Mundo Games" en el carrusel de EmulationStation.
#
# Deja la Toolbox visible como un sistema mas (como TeknoParrot), ademas de en Ports:
#   /userdata/roms/mundogames/            lanzador (+ .keys del mando), imagenes y gamelist.xml
#   configs/emulationstation/es_systems_mundogames.cfg   definicion del sistema
#   <tema>/_inc/logos|anim/mundogames.png                logo y fondo en los temas de /userdata/themes
# Es idempotente: si ya esta todo, no hace nada. Lo ejecutan instalar.sh (consola nueva) y el
# lanzador de la Toolbox (consolas que ya la tenian, al actualizarse).
#
# Uso: sistema.sh [--silencioso]        (necesita MG_URL, o $MG_DIR/servidor.conf)
# Codigo de salida: 0 = ya estaba todo, 10 = hay cambios y EmulationStation debe reiniciarse
#                   para mostrarlos, 1 = fallo.
# Rutas sobreescribibles para pruebas: MG_DIR MG_ROMS MG_ES_CFG MG_TEMAS

umask 022
MG_DIR="${MG_DIR:-/userdata/system/mundogames}"
[ -z "$MG_URL" ] && [ -f "$MG_DIR/servidor.conf" ] && . "$MG_DIR/servidor.conf"
ROMS="${MG_ROMS:-/userdata/roms}"
CFG_DIR="${MG_ES_CFG:-/userdata/system/configs/emulationstation}"
TEMAS="${MG_TEMAS:-/userdata/themes}"
SIS="$ROMS/mundogames"
LANZ="MundoGamesToolbox.sh"
SILENCIO=0; [ "$1" = "--silencioso" ] && SILENCIO=1

dice() { [ "$SILENCIO" = 1 ] || echo "$*"; }
log()  { mkdir -p "$MG_DIR/logs"; echo "$(date '+%F %T') $*" >> "$MG_DIR/logs/toolbox.log"; }
baja() { curl -fsSL --retry 3 --connect-timeout 10 -m 120 -o "$2.mgtmp" "$1" 2>/dev/null && mv -f "$2.mgtmp" "$2" \
             || { rm -f "$2.mgtmp"; return 1; }; }

# Batocera 40 y la "41cp" no traen xmlstarlet. En esas consolas esta funcion en Python hace lo poco
# que la Toolbox usa de xmlstarlet para editar las listas de juegos (gamelist.xml). Si la consola tiene
# xmlstarlet, se usa el de verdad y esto no se define. Admite solo:
#   ed -L (-d RUTA | -s RUTA -t elem -n NOMBRE -v VALOR)... ARCHIVO
#   sel -t -v "count(RUTA)" ARCHIVO        sel -t -m RUTA (-v CAMPO | -n)... ARCHIVO
# RUTA: /gameList, /gameList/game[last()], /gameList/game[path='X'] (o "X") y
#       /gameList/game[contains(translate(path,'A..Z','a..z'),'x')]
# (Mismo bloque en instalar.sh, "Instalar Mundo Games Toolbox.sh", toolbox/lib.sh y toolbox/sistema.sh:
#  si cambias uno, cambia los otros.)
if ! type -P xmlstarlet >/dev/null; then
xmlstarlet() {
    python3 - "$@" <<'MG_PY'
import os, re, sys, xml.etree.ElementTree as ET

def falla(texto):
    sys.exit("xmlstarlet (Python): " + texto)

def leer(archivo):
    try:
        return ET.parse(archivo, ET.XMLParser(target=ET.TreeBuilder(insert_comments=True)))
    except (ET.ParseError, OSError) as e:
        print("xmlstarlet (Python): %s: %s" % (archivo, e), file=sys.stderr)
        sys.exit(3)     # como xmlstarlet

def nodos(raiz, ruta):
    if ruta == "/gameList":
        return [raiz]
    m = re.fullmatch(r"/gameList/game(?:\[(.*)\])?", ruta)
    if not m:
        falla("ruta no soportada: " + ruta)
    juegos, filtro = raiz.findall("game"), m.group(1)
    if filtro is None:
        return juegos
    if filtro == "last()":
        return juegos[-1:]
    m = re.fullmatch(r"path=(['\"])(.*)\1", filtro)
    if m:
        return [g for g in juegos if (g.findtext("path") or "") == m.group(2)]
    m = re.fullmatch(r"contains\(translate\(path,'[A-Z]+','[a-z]+'\),'([^']*)'\)", filtro)
    if m:
        return [g for g in juegos if m.group(1) in (g.findtext("path") or "").lower()]
    falla("ruta no soportada: " + ruta)

def ed(args):
    if len(args) < 2 or args[0] != "-L":
        falla("solo se admite ed -L")
    archivo, ops, i = args[-1], args[1:-1], 0
    arbol = leer(archivo)
    raiz = arbol.getroot()
    while i < len(ops):
        if ops[i] == "-d" and i + 1 < len(ops):
            for g in nodos(raiz, ops[i + 1]):
                if g is raiz:
                    falla("no se puede borrar /gameList")
                raiz.remove(g)
            i += 2
        elif ops[i] == "-s" and ops[i + 2:i + 5] == ["-t", "elem", "-n"] and ops[i + 6:i + 7] == ["-v"] \
                and i + 7 < len(ops):
            for n in nodos(raiz, ops[i + 1]):
                ET.SubElement(n, ops[i + 5]).text = ops[i + 7] or None
            i += 8
        else:
            falla("opcion no soportada: " + " ".join(ops[i:]))
    if hasattr(ET, "indent"):
        ET.indent(arbol, "\t")
    tmp = archivo + ".mgtmp"
    arbol.write(tmp, encoding="utf-8", xml_declaration=True)
    with open(tmp, "a") as f:
        f.write("\n")
    os.chmod(tmp, os.stat(archivo).st_mode & 0o7777)
    os.replace(tmp, archivo)

def sel(args):
    if len(args) < 4 or args[0] != "-t":
        falla("solo se admite sel -t")
    archivo, ops = args[-1], args[1:-1]
    raiz = leer(archivo).getroot()
    if ops[0] == "-v" and len(ops) == 2 and re.fullmatch(r"count\((.*)\)", ops[1]):
        print(len(nodos(raiz, ops[1][6:-1])))
    elif ops[0] == "-m" and len(ops) > 1:
        salida, elegidos = [], nodos(raiz, ops[1])
        for g in elegidos:
            i = 2
            while i < len(ops):
                if ops[i] == "-v" and i + 1 < len(ops):
                    salida.append(g.findtext(ops[i + 1]) or "")
                    i += 2
                elif ops[i] == "-n":
                    salida.append("\n")
                    i += 1
                else:
                    falla("opcion no soportada: " + ops[i])
        sys.stdout.write("".join(salida))
        sys.exit(0 if elegidos else 1)      # como xmlstarlet: 1 si no hay coincidencias
    else:
        falla("solo se admite sel -t -v count(...) o sel -t -m")

if sys.argv[1:2] == ["ed"]:
    ed(sys.argv[2:])
elif sys.argv[1:2] == ["sel"]:
    sel(sys.argv[2:])
else:
    falla("orden no soportada: " + " ".join(sys.argv[1:]))
MG_PY
}
fi

[ -n "$MG_URL" ] || { dice "  [X] Falta la direccion del servidor (MG_URL)."; exit 1; }
mkdir -p "$SIS/images" "$CFG_DIR" || exit 1
cambio=0; cambio_medios=0

# 1) Lanzador y controles del mando (si ya estan, el propio lanzador se actualiza solo)
for f in "$LANZ" "$LANZ.keys"; do
    [ -f "$SIS/$f" ] && continue
    baja "$MG_URL/toolbox/$f" "$SIS/$f" || { dice "  [X] No se pudo descargar $f"; exit 1; }
done
chmod 755 "$SIS/$LANZ"

# medio URL DESTINO: descarga la imagen si falta o si su tamano en el servidor cambio (imagenes
# renovadas); asi las consolas que ya la tenian reciben el diseno nuevo. Marca cambio=1 si hay novedad.
medio() {
    local url="$1" dest="$2" rem loc
    if [ -f "$dest" ]; then
        rem=$(curl -sIL --connect-timeout 8 -m 20 "$url" 2>/dev/null | tr -d '\r' | awk 'tolower($1)=="content-length:" {l=$2} END {print l}')
        loc=$(stat -c%s "$dest" 2>/dev/null)
        { [ -z "$rem" ] || [ "$rem" = "$loc" ]; } && return 0
    fi
    if [ -f "$dest" ]; then cambio_medios=1; else cambio=1; fi     # renovada vs nueva
    baja "$url" "$dest" || return 1
}

# 2) Imagenes de la ficha (las mismas de Ports; en Ports solo si la Toolbox ya esta alli)
declare -A IMG=( [mundogames-toolbox-image.png]=toolbox-image.png [mundogames-toolbox-marquee.png]=toolbox-marquee.png )
for f in "${!IMG[@]}"; do
    medio "$MG_URL/toolbox/media/${IMG[$f]}" "$SIS/images/$f" || { dice "  [X] No se pudo descargar $f"; exit 1; }
    [ -f "$ROMS/ports/images/$f" ] && medio "$MG_URL/toolbox/media/${IMG[$f]}" "$ROMS/ports/images/$f"
done

# 3) Entrada en la lista de juegos del sistema
GL="$SIS/gamelist.xml"
[ -f "$GL" ] || echo '<?xml version="1.0"?><gameList></gameList>' > "$GL"
if [ "$(xmlstarlet sel -t -v "count(/gameList/game[path='./$LANZ'])" "$GL" 2>/dev/null)" != 1 ]; then
    xmlstarlet ed -L -d "/gameList/game[path='./$LANZ']" "$GL" 2>/dev/null
    xmlstarlet ed -L \
        -s "/gameList" -t elem -n "game" -v "" \
        -s "/gameList/game[last()]" -t elem -n "path" -v "./$LANZ" \
        -s "/gameList/game[last()]" -t elem -n "name" -v "Mundo Games Toolbox" \
        -s "/gameList/game[last()]" -t elem -n "desc" -v "Herramientas Mundo Games: descarga e instala juegos ya configurados para tu Retro Mini 3." \
        -s "/gameList/game[last()]" -t elem -n "image" -v "./images/mundogames-toolbox-image.png" \
        -s "/gameList/game[last()]" -t elem -n "marquee" -v "./images/mundogames-toolbox-marquee.png" \
        -s "/gameList/game[last()]" -t elem -n "developer" -v "Mundo Games" \
        -s "/gameList/game[last()]" -t elem -n "publisher" -v "Mundo Games" \
        -s "/gameList/game[last()]" -t elem -n "genre" -v "Toolbox" \
        -s "/gameList/game[last()]" -t elem -n "lang" -v "es" \
        "$GL" || { dice "  [X] No se pudo editar gamelist.xml"; exit 1; }
    cambio=1
fi

# 4) Definicion del sistema en EmulationStation
CFG="$CFG_DIR/es_systems_mundogames.cfg"
if baja "$MG_URL/sistemas/es_systems_mundogames.cfg" "$CFG.nuevo"; then
    if ! cmp -s "$CFG.nuevo" "$CFG"; then mv -f "$CFG.nuevo" "$CFG"; cambio=1; else rm -f "$CFG.nuevo"; fi
elif [ ! -f "$CFG" ]; then
    dice "  [X] No se pudo descargar la definicion del sistema."; exit 1
fi

# 5) Arte del sistema en los temas instalados en /userdata/themes (estilo ckau-book), como el de las demas
#    consolas: logo de la rueda (_inc/logos), televisor retro de fondo (_inc/anim), video de la intro que se
#    reproduce en su pantalla (_inc/anim/video), diseno que lo coloca (_inc/layouts) y color de fondo del
#    sistema (elements/syscolors.xml). Los temas de fabrica (solo lectura) mostraran el nombre como texto.
TEMA_URL="$MG_URL/sistemas/tema"
SYSCOLOR='    <sysColor if="${system.theme} == '"'"'mundogames'"'"'">c0408a</sysColor>'
for t in "$TEMAS"/*/; do
    [ -d "${t}_inc/logos" ] || continue
    mkdir -p "${t}_inc/anim/video" "${t}_inc/layouts"
    medio "$MG_URL/toolbox/media/toolbox-marquee.png" "${t}_inc/logos/mundogames.png"
    medio "$TEMA_URL/mundogames-anim.png"             "${t}_inc/anim/mundogames.png"
    medio "$TEMA_URL/mundogames.mp4"                  "${t}_inc/anim/video/mundogames.mp4"
    medio "$TEMA_URL/mundogames-layout.xml"           "${t}_inc/layouts/mundogames.xml"
    SC="${t}_inc/elements/syscolors.xml"
    if [ -f "$SC" ] && ! grep -q "== 'mundogames'" "$SC"; then
        cp -p "$SC" "$SC.bak-mundogames"
        awk -v l="$SYSCOLOR" '/<\/variables>/ && !hecho {print l; hecho=1} {print}' "$SC" > "$SC.mgtmp" \
            && mv -f "$SC.mgtmp" "$SC" && cambio_medios=1
    fi
done

if [ "$cambio" = 1 ]; then
    log "Sistema Mundo Games agregado/actualizado en EmulationStation"
    dice "  Sistema Mundo Games listo (hay que reiniciar EmulationStation para verlo)."
    exit 10
fi
if [ "$cambio_medios" = 1 ]; then
    log "Imagenes de Mundo Games renovadas (se ven al reiniciar EmulationStation)"
    dice "  Imagenes de Mundo Games renovadas."
fi
dice "  Sistema Mundo Games ya estaba instalado."
exit 0
