#!/bin/bash
# Mundo Games Toolbox - arreglo-harley. Lanza Harley-Davidson: King of the Road (Lindbergh) con el loader
# AppImage de abril de 2025 (el que traia el juego en la Batocera 41, con su propia Mesa 25.0.3).
# Con el loader de Batocera 43.1 + Mesa 25.3.6 el juego pierde memoria de video (bloques i915.gem de 2 MB
# que no se liberan) y se cierra solo a los ~4,5 min. Con este loader la memoria queda estable.
#
# Lo llama lindbergh-sqfs-launcher.sh (bloque "mundogames arreglo-harley") con el emulador sh, asi
# Batocera sigue pasando el mando y evmapy lee harley.sh.keys (Hotkey+Start cierra el juego). El bloque
# exporta MG_HARLEY_SQFS (el .sqfs elegido) y MG_HARLEY_P1DEV / MG_HARLEY_P1GUID (mando del jugador 1).
# Monta el .sqfs con un overlay propio; partidas y ajustes en saves/lindbergh/hdkotr-mundogames.
# Registro de la ultima partida: /userdata/system/logs/arreglo-harley.log

K=/userdata/system/mundogames/arreglo-harley
SQFS="${MG_HARLEY_SQFS:-/userdata/roms/lindbergh/hdkotr.sqfs}"
S=/userdata/saves/lindbergh/hdkotr-mundogames
B=/run/mundogames-harley
RO=$B/ro; M=$B/merged
exec > /userdata/system/logs/arreglo-harley.log 2>&1
echo "$(date) $SQFS mando=${MG_HARLEY_P1DEV:-?}"
fallo() { echo "ERROR: $*"; exit 1; }

# Una partida anterior que no se cerro bien (o sus montajes) impediria abrir esta: el juego daria error 6009.
pkill -f "$K/loader/usr/bin/lindbergh"; pkill -x chopperM.elf
sleep 1; pkill -9 -x chopperM.elf
montado() { grep -q " $1 " /proc/mounts; }
for m in "$M" "$RO"; do montado "$m" && { umount "$m" || umount -l "$m"; }; done

[ -f "$SQFS" ] || fallo "no esta $SQFS"
mkdir -p "$RO" "$M" "$S/upper" "$S/work" "$K/home" || fallo "no se pudieron crear las carpetas"
cleanup() { cd /; umount "$M" 2>/dev/null || umount -l "$M"; umount "$RO" 2>/dev/null || umount -l "$RO"; }
trap cleanup EXIT
mount -t squashfs -o loop,ro "$SQFS" "$RO" || fallo "no se pudo montar $SQFS"
mount -t overlay overlay -o "lowerdir=$RO,upperdir=$S/upper,workdir=$S/work" "$M" || fallo "no se pudo montar el overlay"
[ -d "$M/elf" ] || fallo "el juego no tiene la carpeta elf/"

# sram/eeprom ya configuradas: con unas nuevas el juego no se entiende con el mueble emulado (error 7703)
for f in sram.bin eeprom.bin; do
    [ -s "$S/$f" ] || cp "$K/inicial/$f" "$S/$f" || fallo "no se pudo copiar $f (falta espacio?)"
done

# Ajustes del loader + controles del mando del jugador 1 (mismo mapeo que usa Batocera para Harley)
{ sed -e "s#^SRAM_PATH .*#SRAM_PATH $S/sram.bin#" -e "s#^EEPROM_PATH .*#EEPROM_PATH $S/eeprom.bin#" "$K/lindbergh.conf.base"
  python3 "$K/mandos.py"
} > "$M/elf/lindbergh.conf" && [ -s "$M/elf/lindbergh.conf" ] || fallo "no se pudo escribir lindbergh.conf (falta espacio?)"
grep -E "^(PLAYER_1|ANALOGUE)" "$M/elf/lindbergh.conf" || echo "sin controles del mando: el loader usa el teclado"

cd "$M/elf" || fallo "no se pudo entrar en elf/"
export HOME="$K/home"
export LD_LIBRARY_PATH=./lib:/lib32
export LIBGL_DRIVERS_PATH=/lib32/dri
export SPA_PLUGIN_DIR="/lib32/spa-0.2:/usr/lib/spa-0.2"
export PIPEWIRE_MODULE_DIR="/lib32/pipewire-0.3:/usr/lib/pipewire-0.3"
"$K/loader/AppRun"
rc=$?
echo "$(date) fin rc=$rc"
# 137/143 = cerrado con Hotkey+Start (pkill): para ES es una salida normal
case $rc in 137|143) exit 0 ;; *) exit $rc ;; esac
