#!/bin/bash
# SPDX-License-Identifier: GPL-3.0-or-later
#
# arm64-proton <proton appid | proton dir> <verb> [args…] — run an ARM64
# Proton build (Valve's by appid, or a compatibilitytools.d one by path) (arm64ec + bundled FEX) inside Steam Linux Runtime 4.0 -
# Arm64 (appid 4185400).
#
# The arm64 Steam client ships these Protons but registers none of them
# in the compatibility-tool picker, and their own toolmanifest requires
# the arm64 runtime as a tool, which the client cannot wrap. The entries
# under /usr/share/steam/compatibilitytools.d call this instead, which
# wraps the runtime's entry point directly. Install directories come from
# the app manifests, so Valve renaming a folder does not break it. When
# Steam's runtime copy is incomplete (its depot comes down empty on this
# client), the one pocketds-steam-install-runtime keeps is used instead.

appid=$1
shift
steamapps="$HOME/.local/share/Steam/steamapps"
log="$HOME/.local/state/pocketds-steam/arm64-proton.log"
mkdir -p "${log%/*}"
{ echo "=== $(date '+%F %T') appid=$appid verb=$1"; env | grep -E '^(STEAM_COMPAT|FEX)' | sort; } >"$log"
exec >>"$log" 2>&1

installdir() {
    sed -n 's/^[[:space:]]*"installdir"[[:space:]]*"\(.*\)"$/\1/p' "$steamapps/appmanifest_$1.acf" 2>/dev/null
}

case $appid in
    /*) proton="$appid/proton" ;;
    *) proton="$steamapps/common/$(installdir "$appid")/proton" ;;
esac
runtime="$steamapps/common/$(installdir 4185400)/_v2-entry-point"
[ -x "$runtime" ] || runtime="${XDG_DATA_HOME:-$HOME/.local/share}/pocketds-steam/SteamLinuxRuntime_4-arm64/_v2-entry-point"

if [ ! -x "$proton" ]; then
    echo "Proton $appid is not installed"
    exit 1
fi
if [ ! -x "$runtime" ]; then
    echo "Steam Linux Runtime 4.0 - Arm64 is missing: run pocketds-steam-install-runtime"
    exit 1
fi

exec "$runtime" --verb="$1" -- "$proton" "$@"
