#!/bin/sh
# The Hookshot AppImage: the builder window (builder/linux/hookshot_builder.py) with everything it builds the game with -
# Python and the tools, clang and lld, a glibc 2.35 sysroot, FFmpeg, SDL2 and the Vulkan back end, built already.
#   Hookshot.AppImage                  the launcher window (Play is in the window, once a game is built)
#   Hookshot.AppImage --classic        the classic builder window instead
#   Hookshot.AppImage --play           start the game the builder saved, without opening the window
#   Hookshot.AppImage --play <folder>  start the game in that folder
#   Hookshot.AppImage <folder>         the same
#   Hookshot.AppImage --cli <args>     nx2/make_game.py itself, e.g. --cli --nup game.nup --out ~/Games/Hookshot
#   Hookshot.AppImage --launch <dir>  the game folder's launcher: Play, and Update when a newer release is out
#   Hookshot.AppImage --update <dir>  download the new release (only the parts that changed) and build that folder again
HERE="$(dirname "$(readlink -f "$0")")"
LIB="$HERE/usr/lib/hookshot"
export HOOKSHOT_TOOLS="$HERE/usr/share/hookshot"
export EMSDK="$LIB/emsdk"
export HOOKSHOT_SYSROOT="$LIB/sysroot"
export HOOKSHOT_FFMPEG="$LIB/ffmpeg"
export HOOKSHOT_VK_PREBUILT="$LIB/hookshot_vk.so"
export HOOKSHOT_SDL2="$LIB/libSDL2-2.0.so.0"
# (written into the game folder's hookshot_version.txt, so its launcher finds this builder)
if [ -n "${APPIMAGE:-}" ]; then
    export HOOKSHOT_BUILDER_EXE="$APPIMAGE"
else
    export HOOKSHOT_BUILDER_EXE="$HERE/AppRun"
fi
PY="$HERE/usr/python/bin/python3"
if [ "${1:-}" = "--cli" ]; then
    shift
    exec "$PY" -I "$HOOKSHOT_TOOLS/nx2/make_game.py" "$@"
fi
# Play is the same AppImage: the start script drops this image's libraries, then runs the built game.
if [ "${1:-}" = "--play" ]; then
    shift
    exec "$HOOKSHOT_TOOLS/builder/linux/hookshot-launch" "$@"
fi
if [ -n "${1:-}" ] && [ -d "$1" ]; then
    exec "$HOOKSHOT_TOOLS/builder/linux/hookshot-launch" "$1"
fi
# The window: the Triforce launcher (usr/bin/triforce-launcher, a WebKitGTK window). It exits 4 when this system has no
# WebKitGTK 4.1 (e.g. some Steam Deck images), and the classic builder window opens instead; --classic or
# TRIFORCE_CLASSIC=1 always opens the classic one.
LAUNCHER="$HERE/usr/bin/triforce-launcher"
if [ "${1:-}" = "--classic" ]; then
    shift
    TRIFORCE_CLASSIC=1
fi
if [ "${TRIFORCE_CLASSIC:-0}" != "1" ] && [ -x "$LAUNCHER" ]; then
    # (WebKitGTK's GPU path breaks on NVIDIA's driver and under gamescope; its plain path is fine for a launcher)
    export WEBKIT_DISABLE_DMABUF_RENDERER="${WEBKIT_DISABLE_DMABUF_RENDERER:-1}"
    export TRIFORCE_APPRUN="$HERE/AppRun"
    "$LAUNCHER" "$@"
    code=$?
    [ "$code" -ne 4 ] && exit "$code"
fi
exec "$PY" -I "$HOOKSHOT_TOOLS/builder/linux/hookshot_builder.py" "$@"
