#!/bin/sh
# AppImage entry point. Tokens are stamped by tools/package_appimage.sh.
set -eu

if [ -z "${APPDIR:-}" ]; then
    echo "@APP_NAME@: APPDIR is not set; launch this through the AppImage runtime." >&2
    exit 1
fi

if [ -n "${@ENV_PREFIX@_DATA_DIR:-}" ]; then
    data_dir=$@ENV_PREFIX@_DATA_DIR
elif [ -n "${XDG_DATA_HOME:-}" ]; then
    data_dir=$XDG_DATA_HOME/@EXE_NAME@
elif [ -n "${HOME:-}" ]; then
    data_dir=$HOME/.local/share/@EXE_NAME@
else
    echo "@APP_NAME@: HOME is not set; set @ENV_PREFIX@_DATA_DIR explicitly." >&2
    exit 1
fi

payload=$APPDIR/usr/share/@PAYLOAD_DIR@
runtime=$APPDIR/usr/bin/@EXE_NAME@
if [ ! -x "$runtime" ] || [ ! -f "$payload/game.toml" ]; then
    echo "@APP_NAME@: AppImage payload is incomplete." >&2
    exit 1
fi

mkdir -p "$data_dir" "$data_dir/saves" "$data_dir/cache" "$data_dir/mods"

# Refresh release-owned resources, but preserve settings, saves, third-party
# mods, and generated cache entries.
for tree in assets bios licenses docs tools; do
    if [ -d "$payload/$tree" ]; then
        mkdir -p "$data_dir/$tree"
        cp -a "$payload/$tree/." "$data_dir/$tree/"
        chmod -R u+rwX "$data_dir/$tree"
    fi
done
if [ -d "$payload/mods" ]; then
    cp -a "$payload/mods/." "$data_dir/mods/"
    chmod -R u+rwX "$data_dir/mods"
fi

# Release shards fill gaps only. A cache grown by the player must survive an
# AppImage update and every subsequent launch.
if [ -d "$payload/cache" ]; then
    mkdir -p "$data_dir/cache"
    cp -a -n "$payload/cache/." "$data_dir/cache/" 2>/dev/null || true
    chmod -R u+rwX "$data_dir/cache"
fi

# Link the read-only bundled overlay toolchain into the writable data directory.
# The runtime looks beside argv[0], and argv[0] is the launcher symlink below.
if [ -d "$payload/overlay_toolchain" ]; then
    if [ -L "$data_dir/overlay_toolchain" ] || [ ! -e "$data_dir/overlay_toolchain" ]; then
        ln -sfn "$payload/overlay_toolchain" "$data_dir/overlay_toolchain"
    fi
fi
for file in game.toml LICENSE THIRD_PARTY_NOTICES.md DISC.md README.md RELEASE_NOTES.md APPIMAGE_README.md START_HERE.txt; do
    if [ -f "$payload/$file" ]; then
        cp -f "$payload/$file" "$data_dir/$file"
        chmod u+rw "$data_dir/$file"
    fi
done
if [ ! -f "$data_dir/input.ini" ] && [ -f "$payload/input.ini" ]; then
    cp "$payload/input.ini" "$data_dir/input.ini"
    chmod u+rw "$data_dir/input.ini"
fi
printf '%s\n' "@VERSION@" > "$data_dir/.appimage-layout-version"

if [ "${@ENV_PREFIX@_SEED_ONLY:-0}" = "1" ]; then
    printf '%s\n' "$data_dir"
    exit 0
fi

# psxrecomp anchors writable paths to argv[0]. Invoke through a symlink in the
# writable data directory instead of exposing the read-only squashfs path.
launcher=$data_dir/.@EXE_NAME@-runtime
ln -sfn "$runtime" "$launcher"
appimage_path=${APPIMAGE:-}
export @ENV_PREFIX@_APPIMAGE_PATH=$appimage_path
export RECOMP_APPIMAGE_PATH=$appimage_path

# Give the dependency-free in-launcher browser a useful starting selection.
# A disc is never bundled. We only expose a hint when the player has placed a
# legal .cue next to the AppImage or in the repository's sibling mmx4 folder.
if [ -z "${RECOMP_DISC_HINT:-}" ] && [ -n "$appimage_path" ]; then
    appimage_dir=$(dirname -- "$appimage_path")
    for candidate in "$appimage_dir"/*.cue "$appimage_dir"/../mmx4/*.cue; do
        if [ -f "$candidate" ]; then
            RECOMP_DISC_HINT=$candidate
            export RECOMP_DISC_HINT
            break
        fi
    done
fi

# An explicit validation/runtime override may preselect a disc without baking
# a developer path into the reproducible release configuration.
disc_override=${@ENV_PREFIX@_DISC:-}
if [ -n "$disc_override" ] && [ -f "$disc_override" ]; then
    config_tmp=$data_dir/.game.toml.tmp
    awk -v disc="$disc_override" '
        BEGIN { inserted = 0 }
        /^[[:space:]]*disc[[:space:]]*=/ { next }
        /^\[/ && $0 != "[game]" && !inserted {
            escaped = disc
            gsub(/\\/, "\\\\", escaped)
            gsub(/"/, "\\\"", escaped)
            print "disc = \"" escaped "\""
            inserted = 1
        }
        { print }
    ' "$data_dir/game.toml" > "$config_tmp"
    mv "$config_tmp" "$data_dir/game.toml"
fi
unset APPIMAGE

export PATH="$APPDIR/usr/bin${PATH:+:$PATH}"
export LD_LIBRARY_PATH="$APPDIR/usr/lib${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}"
export XDG_DATA_DIRS="$APPDIR/usr/share${XDG_DATA_DIRS:+:$XDG_DATA_DIRS}"

cd "$data_dir"
exec "$launcher" "$@"
