#!/usr/bin/env python3
# Mundo Games Toolbox - arreglo-harley. Lo ejecuta post_instalar de la receta (idempotente):
#   aplicar.py RAIZ        (RAIZ = /userdata, o una copia para pruebas)
# 1. Comprueba que la consola tenga Harley en Lindbergh (hdkotr.sqfs) lanzado por lindbergh-sqfs-launcher.sh.
# 2. Pone en el lanzador el bloque "mundogames arreglo-harley": hdkotr.sqfs pasa a lanzarse con
#    system/mundogames/arreglo-harley/harley.sh (emulador sh). Los demas juegos Lindbergh no cambian, y si
#    falta el kit (o existe arreglo-harley/DESACTIVADO) Harley vuelve al loader de Batocera.
# 3. Borra todo lo que dejaba la version que falla (loader de Batocera): su overlay de hdkotr, su sram y
#    eeprom, y las lineas de Harley en batocera.conf (lindbergh["hdkotr.game"], lindberghsh["Harley...sh"]).
import os
import re
import shutil
import sys

R = sys.argv[1].rstrip("/")
LANZADOR = f"{R}/system/lindbergh-sqfs-launcher.sh"
ES_CFG = f"{R}/system/configs/emulationstation/es_systems_lindbergh.cfg"
CONF = f"{R}/system/batocera.conf"
SAVES = f"{R}/saves/lindbergh"

BLOQUE = """# >>> mundogames arreglo-harley (Mundo Games Toolbox): Harley con el loader de abril de 2025.
# Con el loader de Batocera pierde memoria de video y se cierra solo a los pocos minutos.
# Si falta el kit, o existe system/mundogames/arreglo-harley/DESACTIVADO, vuelve al loader de Batocera.
MG_HARLEY=/userdata/system/mundogames/arreglo-harley
if [[ "$ROM" == */hdkotr.sqfs ]] && [ -x "$MG_HARLEY/harley.sh" ] && [ ! -e "$MG_HARLEY/DESACTIVADO" ]; then
  NEWARGS=()
  prev=""
  for a in "$@"; do
    if [ "$prev" = "-rom" ]; then NEWARGS+=("$MG_HARLEY/harley.sh"); else NEWARGS+=("$a"); fi
    case "$prev" in
      -p1devicepath) export MG_HARLEY_P1DEV="$a" ;;
      -p1guid) export MG_HARLEY_P1GUID="$a" ;;
    esac
    prev="$a"
  done
  export MG_HARLEY_SQFS="$ROM"
  emulatorlauncher "${NEWARGS[@]}" -emulator sh -core sh
  EXITCODE=$?
  echo "$(date) exit=$EXITCODE (arreglo-harley)" >> "$LOG"
  exit $EXITCODE
fi
# <<< mundogames arreglo-harley
"""


def fallar(texto):
    print(f"arreglo-harley: {texto}")
    sys.exit(1)


def escribir(ruta, texto):
    tmp = ruta + ".mgtmp"
    with open(tmp, "w", encoding="utf-8") as f:
        f.write(texto)
    if os.path.exists(ruta):
        os.chmod(tmp, os.stat(ruta).st_mode & 0o7777)
    os.replace(tmp, ruta)


# 1. Requisitos
if not os.path.isfile(f"{R}/roms/lindbergh/hdkotr.sqfs"):
    fallar("no esta roms/lindbergh/hdkotr.sqfs")
if not os.path.isfile(LANZADOR):
    fallar("no esta system/lindbergh-sqfs-launcher.sh")
try:
    if "lindbergh-sqfs-launcher.sh" not in open(ES_CFG, encoding="utf-8").read():
        fallar("es_systems_lindbergh.cfg no usa lindbergh-sqfs-launcher.sh")
except OSError:
    fallar("no esta es_systems_lindbergh.cfg")

# 2. Lanzador: quitar un bloque anterior y poner el actual justo antes de 'case "$ROM" in'
#    (ahi ya estan definidos $LOG y $ROM)
texto = open(LANZADOR, encoding="utf-8").read()
texto = re.sub(r"^[ \t]*# >>> mundogames arreglo-harley.*?# <<< mundogames arreglo-harley[^\n]*\n", "",
               texto, flags=re.S | re.M)
anclas = list(re.finditer(r'^case "\$ROM" in[ \t]*\r?$', texto, flags=re.M))
if len(anclas) != 1:
    fallar("el lanzador no tiene la forma esperada (case \"$ROM\" in)")
i = anclas[0].start()
escribir(LANZADOR, texto[:i] + BLOQUE + texto[i:])
print("arreglo-harley: lanzador listo")

# 3. Rastros de la version que falla
borrar = [f"{SAVES}/overlay/hdkotr", f"{SAVES}/sram.bin.hdkotr", f"{SAVES}/eeprom.bin.hdkotr"]
for ruta in borrar:
    if os.path.isdir(ruta) and not os.path.islink(ruta):
        shutil.rmtree(ruta)
        print(f"arreglo-harley: borrado {ruta}")
    elif os.path.lexists(ruta):
        os.remove(ruta)
        print(f"arreglo-harley: borrado {ruta}")

if os.path.isfile(CONF):
    lineas = open(CONF, encoding="utf-8").read().splitlines(keepends=True)
    viejas = re.compile(r'^\s*(lindbergh\["hdkotr\.(game|sqfs)"\]|lindberghsh\["Harley Davidson - King of the Road\.sh"\])[.-]')
    quedan = [l for l in lineas if not viejas.match(l)]
    if len(quedan) != len(lineas):
        escribir(CONF, "".join(quedan))
        print(f"arreglo-harley: {len(lineas) - len(quedan)} lineas de Harley quitadas de batocera.conf")
