#!/bin/bash
# Instala la Mundo Games Toolbox en el menu Ports de Batocera.
# Uso (terminal de Batocera o SSH):
#   curl -fsSL https://raspberrypi.tailc33149.ts.net/mundogames/instalar.sh | bash
# Se puede ejecutar varias veces: reemplaza la entrada anterior sin duplicarla.

set -e
MG_URL="https://raspberrypi.tailc33149.ts.net/mundogames"
PORTS="/userdata/roms/ports"
LANZADOR="MundoGamesToolbox.sh"
GAMELIST="$PORTS/gamelist.xml"
MG_DIR="/userdata/system/mundogames"

# fallo "texto": explica el error en pantalla, lo anota en toolbox.log (con la version de Batocera,
# para diagnosticar por red sin la foto) y termina. El motivo lo da siempre este script: el
# instalador de un clic solo avisa de que fallo, asi los mensajes se mejoran publicando en la NAS.
fallo() {
    echo "  [X] $*"
    { mkdir -p "$MG_DIR/logs" && echo "$(date '+%F %T') ERROR instalar.sh (Batocera $(cut -d' ' -f1 /usr/share/batocera/batocera.version)): $*" \
        >> "$MG_DIR/logs/toolbox.log"; } 2>/dev/null || true
    exit 1
}
# Cualquier otro fallo (el que haria cortar "set -e") tambien queda explicado y anotado.
trap 'fallo "Error inesperado en la linea $LINENO: $BASH_COMMAND"' ERR

# Direcciones IP de un servidor, una por linea (IPv4 primero).
mg_direcciones() {
    python3 -c 'import socket, sys
ips = []
for fam in (socket.AF_INET, socket.AF_INET6):
    try: ips += [a[4][0] for a in socket.getaddrinfo(sys.argv[1], 443, fam, socket.SOCK_STREAM)]
    except OSError: pass
print("\n".join(dict.fromkeys(ips)))' "$1" 2>/dev/null \
    || getent ahosts "$1" 2>/dev/null | awk '{print $1}' | awk '!visto[$0]++'
}

# mg_bajar URL DESTINO: descarga con reintentos. Tailscale Funnel tiene varios relays y el DNS los
# reparte; si uno falla corta la conexion segura (curl 35), y "curl --retry" no reintenta ese error
# ni cambia de relay. Por eso, si el intento normal falla, se prueba cada direccion del servidor
# por separado (--resolve), en 3 rondas. Si todo falla muestra el ultimo error de curl.
# (Misma funcion que en "Instalar Mundo Games Toolbox.sh": si cambias una, cambia la otra.)
mg_bajar() {
    local url="$1" dest="$2" host puerto ip ronda err=""
    host="${url#*://}"; host="${host%%/*}"
    case "$url" in https://*) puerto=443 ;; *) puerto=80 ;; esac
    for ronda in 1 2 3; do
        for ip in "" $(mg_direcciones "$host"); do
            if [ -z "$ip" ]; then
                set -- -o "$dest.mgtmp" "$url"
            else
                case "$ip" in *:*) ip="[$ip]" ;; esac
                set -- --resolve "$host:$puerto:$ip" -o "$dest.mgtmp" "$url"
            fi
            if err=$(curl -fsSL --connect-timeout 10 -m 120 "$@" 2>&1); then
                mv -f "$dest.mgtmp" "$dest" && return 0
            fi
            case "$err" in *"error: 40"*) break 2 ;; esac      # el archivo no existe: no insistir
            [ "$ronda$ip" = 1 ] && echo "   (conexion inestable con el servidor, reintentando...)"
        done
        [ "$ronda" -lt 3 ] && sleep $((ronda * 3))
    done
    rm -f "$dest.mgtmp"
    echo "   ${err:-sin respuesta del servidor}"
    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

[ "$(uname -m)" = "x86_64" ] || fallo "Consola no compatible ($(uname -m))."
# Programas que necesita la instalacion: se comprueban ANTES de tocar nada para no dejarla a medias.
# Sin xmlstarlet (Batocera 40 y la 41cp) se usa la funcion en Python de arriba, que necesita python3.
# Ojo: "command -v xmlstarlet" tambien encuentra esa funcion; "type -P" solo busca el programa.
command -v curl >/dev/null || fallo "A esta consola le falta el programa 'curl' (su Batocera parece modificada). No se instalo nada."
type -P xmlstarlet >/dev/null || type -P python3 >/dev/null \
    || fallo "A esta consola le faltan los programas 'xmlstarlet' y 'python3' (su Batocera parece modificada). No se instalo nada."

echo ">> Instalando Mundo Games Toolbox en Ports..."
mkdir -p "$PORTS/images" "$MG_DIR/backups" "$MG_DIR/logs"
echo "MG_URL=\"$MG_URL\"" > "$MG_DIR/servidor.conf"   # unico lugar con la direccion del servidor
mg_bajar "$MG_URL/toolbox/$LANZADOR"      "$PORTS/$LANZADOR"      || fallo "No se pudo descargar $LANZADOR"
mg_bajar "$MG_URL/toolbox/$LANZADOR.keys" "$PORTS/$LANZADOR.keys" || fallo "No se pudo descargar $LANZADOR.keys"
mg_bajar "$MG_URL/toolbox/media/toolbox-image.png"   "$PORTS/images/mundogames-toolbox-image.png"   || fallo "No se pudo descargar la imagen de la Toolbox"
mg_bajar "$MG_URL/toolbox/media/toolbox-marquee.png" "$PORTS/images/mundogames-toolbox-marquee.png" || fallo "No se pudo descargar el logo de la Toolbox"
chmod +x "$PORTS/$LANZADOR"

echo ">> Agregando la Toolbox a la lista de Ports..."
[ -f "$GAMELIST" ] || echo '<?xml version="1.0"?><gameList></gameList>' > "$GAMELIST"
cp -p "$GAMELIST" "$MG_DIR/backups/ports-gamelist.xml.$(date +%Y%m%d-%H%M%S)"
xmlstarlet ed -L -d "/gameList/game[path='./$LANZADOR']" "$GAMELIST"
xmlstarlet ed -L \
    -s "/gameList" -t elem -n "game" -v "" \
    -s "/gameList/game[last()]" -t elem -n "path" -v "./$LANZADOR" \
    -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" \
    "$GAMELIST"

echo "$(date '+%F %T') Toolbox instalada en Ports" >> "$MG_DIR/logs/toolbox.log"

# Tambien como sistema propio en el carrusel de EmulationStation (toolbox/sistema.sh).
# Si falla, la Toolbox sigue disponible en Ports.
echo ">> Agregando Mundo Games al menu principal de EmulationStation..."
rm -f /tmp/mg-reiniciar-es
if mg_bajar "$MG_URL/toolbox/sistema.sh" /tmp/mg-sistema.sh; then
    MG_URL="$MG_URL" bash /tmp/mg-sistema.sh --silencioso && rc=0 || rc=$?
else
    rc=1
fi
rm -f /tmp/mg-sistema.sh
case "$rc" in
    0)  ;;
    10) touch /tmp/mg-reiniciar-es ;;     # hay que reiniciar EmulationStation para ver el sistema
    *)  echo "   (No se pudo agregar al menu principal; la Toolbox sigue en Ports.)" ;;
esac

curl -s -m 10 http://127.0.0.1:1234/reloadgames >/dev/null 2>&1 || true
case "$rc" in
    0|10) echo ">> Listo. Busca 'Mundo Games Toolbox' en Ports y en el sistema Mundo Games." ;;
    *)    echo ">> Listo. Busca 'Mundo Games Toolbox' en Ports." ;;
esac
[ -f /tmp/mg-reiniciar-es ] && echo "   Para ver el sistema Mundo Games, reinicia EmulationStation (Start -> Salir -> Reiniciar EmulationStation)."
exit 0
