#!/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 hookshot in the folder (nx2/make_game.py).
#
# It starts the builder= line in hookshot_version.txt (the builder that made this game), or the installed builder
# ($XDG_DATA_HOME/hookshot/builder) when that one is gone. 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}}/hookshot/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=$(builder_line || true)
if [ -z "$run" ]; then
    run=$(installed || true)
fi
if [ -n "$run" ]; then
    exec "$run" --launch "$HERE"
fi
if [ -x "$HERE/bin/hookshot" ]; then
    cd "$HERE"
    exec ./bin/hookshot
fi
echo "Hookshot: the game (bin/hookshot) is missing from this folder. Build it again with Hookshot Builder." >&2
exit 1
