#!/bin/sh
# Metroid Prime 4 Recomp AppImage: the game is installed outside the (read-only) AppImage, in MP4_RECOMP_HOME or
# ~/.local/share/MetroidPrime4Recomp (METROID_BEYOND_HOME and ~/.local/share/MetroidBeyondRecomp from earlier builds:
# the old variable still works, and the old default folder is moved to the new one once, a rename on the same drive). The runtime finds its .ini, _code.so and _data next to itself, so a copy of it lives
# there, refreshed when this AppImage brings a different one. The Play / setup screen (beyond_ui/fe.cpp) gets the
# recompiler, GCC and Python from inside the AppImage through SWR_RECOMPILER.
HERE="$(dirname "$(readlink -f "$0")")"
DATA="${XDG_DATA_HOME:-$HOME/.local/share}"
GAME="${MP4_RECOMP_HOME:-${METROID_BEYOND_HOME:-$DATA/MetroidPrime4Recomp}}"
if [ -z "$MP4_RECOMP_HOME$METROID_BEYOND_HOME" ] && [ ! -e "$GAME" ] && [ -d "$DATA/MetroidBeyondRecomp" ]; then
  mv "$DATA/MetroidBeyondRecomp" "$GAME" 2>/dev/null || GAME="$DATA/MetroidBeyondRecomp"
fi
mkdir -p "$GAME" || { echo "Cannot create the game folder $GAME" >&2; exit 1; }
if ! cmp -s "$HERE/usr/bin/metroid-prime-4-recomp" "$GAME/Metroid Prime 4 Beyond"; then
  cp -f "$HERE/usr/bin/metroid-prime-4-recomp" "$GAME/Metroid Prime 4 Beyond.new" && chmod +x "$GAME/Metroid Prime 4 Beyond.new" && mv -f "$GAME/Metroid Prime 4 Beyond.new" "$GAME/Metroid Prime 4 Beyond"
fi
[ -d "$GAME/licenses" ] || cp -r "$HERE/usr/share/metroid-prime-4-recomp/licenses" "$GAME/licenses" 2>/dev/null
export SWR_RECOMPILER="$HERE/usr/share/metroid-prime-4-recomp/recompiler"
cd "$GAME" || exit 1
exec "./Metroid Prime 4 Beyond" "$@"
