#!/bin/sh
# The game folder's launcher, what hookshot.exe is on Windows: Play, and Update when a newer release is out.
# The game itself is bin/hookshot. This file is copied to HeyListen in the folder (nx2/make_game.py).
#
# It starts the builder installed by an update ($XDG_DATA_HOME/heylisten/builder), or the builder= line in
# hookshot_version.txt (the AppImage that built the folder). With neither, it starts the game.
set -eu
HERE=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)

installed() {
    root=${HOOKSHOT_BUILDER_HOME:-${XDG_DATA_HOME:-$HOME/.local/share}}/heylisten/builder
    [ -f "$root/current" ] || return 1
    tag=$(tr -d ' \r\n' < "$root/current")
    [ -n "$tag" ] && [ -x "$root/versions/$tag/AppRun" ] || return 1
    printf '%s\n' "$root/versions/$tag/AppRun"
}

builder_line() {
    [ -f "$HERE/hookshot_version.txt" ] || return 1
    path=
    while IFS= read -r line || [ -n "$line" ]; do
        case $line in
            builder=*) path=${line#builder=} ;;
        esac
    done < "$HERE/hookshot_version.txt"
    [ -n "$path" ] && [ -x "$path" ] || return 1
    printf '%s\n' "$path"
}

run=$(installed || true)
if [ -z "$run" ]; then
    run=$(builder_line || true)
fi
if [ -n "$run" ]; then
    exec "$run" --launch "$HERE"
fi
if [ -x "$HERE/bin/hookshot" ]; then
    cd "$HERE"
    exec ./bin/hookshot
fi
echo "HeyListen: the game (bin/hookshot) is missing from this folder. Build it again with HeyListen Builder." >&2
exit 1
