#!/bin/sh
# Shogo: Mobile Armor Division (Linux Demo) - launcher wrapper Flatpak
# Avvia il client i386 in gamescope fullscreen con sdl12-compat (audio PipeWire)
set -eu

export LD_LIBRARY_PATH="/app/lib32:/app/lib/i386-linux-gnu${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}"
export SDL_VIDEODRIVER=x11
export SDL_AUDIODRIVER=pulseaudio
export SDL_AUDIO_DEVICE_SAMPLE_FRAMES=2048
export MESA_EXTENSION_MAX_YEAR=2002
export SHOGODIR=/app/game
export SHOGO_CDROM=/app/game
export SHOGO_MOVIEPATH=/app/game/Movies

# EULA: prima accettazione richiesta, poi persistente
EULA_FILE="${XDG_CONFIG_HOME:-$HOME/.config}/shogo-demo/eula-accepted"
if [ ! -f "$EULA_FILE" ]; then
    mkdir -p "$(dirname "$EULA_FILE")"
    if /app/bin/eula-dialog; then
        touch "$EULA_FILE"
    else
        echo "License not accepted: Shogo will not start."
        exit 1
    fi
fi

# User config (as in the historical port launcher script)
mkdir -p "$HOME/.hyperion/Shogo/Save"
[ -f "$HOME/.hyperion/Shogo/ShogoLauncher.ini" ] || cp /app/game/ShogoLauncher.ini "$HOME/.hyperion/Shogo/" 2>/dev/null || true
# User autoexec.cfg with forced resolution/color (the menu lists up to 1024x768 only,
# but the engine accepts higher values via autoexec.cfg / command line)
if [ ! -f "$HOME/.hyperion/Shogo/autoexec.cfg" ]; then
    {
      echo '"ScreenWidth"  "1024"'
      echo '"ScreenHeight" "768"'
      echo '"MaxFPS"       "30"'
      echo '"MouseSensitivity" "3.000000"'
    } > "$HOME/.hyperion/Shogo/autoexec.cfg"
fi

# Save games in XDG data (writable in the sandbox)
SAVEDIR="${XDG_DATA_HOME:-$HOME/.local/share}/shogo-demo"
mkdir -p "$SAVEDIR/Save"

cd /app/game
RUN="./client +savedirectory \"$SAVEDIR\" -rez shogodem.rez +renderdll glx.ren \
+screenwidth 1024 +screenheight 768 +bpp 16 +Sound16Bit 1 +NumSWVoices 16 \
+DisableSound 0 +DisableMusic 0 +DisableMovies 1 +DisableLightmap 1 \
+EnableTjuncs 1 +EnableMultiTex 1 -conskey 291 +MaxFPS 30"

if command -v gamescope >/dev/null 2>&1; then
    exec gamescope -f -w 1024 -h 768 -S fit --force-grab-cursor -r 60 -- /bin/sh -c "$RUN"
else
    exec /bin/sh -c "$RUN"
fi
