#!/bin/bash
# SPDX-License-Identifier: GPL-3.0-or-later
#
# pocketds-steam-wrap-arm64-tools — make user-installed ARM64 Protons
# (e.g. proton-cachyos-*-arm64 in compatibilitytools.d) start.
#
# Their toolmanifest requires Steam Linux Runtime 4.0 - Arm64 as a tool
# (require_tool_appid 4185400), whose depot comes down empty to this
# client, so Steam never launches them. Point such manifests at
# /usr/libexec/pocketds-steam/arm64-proton, which wraps the runtime
# itself. Runs before Steam starts; tools already rewritten are skipped.

compat="${HOME}/.local/share/Steam/compatibilitytools.d"

for manifest in "$compat"/*/toolmanifest.vdf; do
    [ -f "$manifest" ] || continue
    grep -q '"require_tool_appid"[[:space:]]*"4185400"' "$manifest" || continue
    grep -q '"commandline"[[:space:]]*"/proton %verb%"' "$manifest" || continue
    dir=${manifest%/*}
    [ -x "$dir/proton" ] || continue
    printf '#!/bin/sh\nexec /usr/libexec/pocketds-steam/arm64-proton "$(dirname "$(readlink -f "$0")")" "$@"\n' \
        > "$dir/pocketds-run"
    chmod 755 "$dir/pocketds-run"
    sed -i -e 's|"commandline"\([[:space:]]*\)"/proton %verb%"|"commandline"\1"/pocketds-run %verb%"|' \
        -e '/"require_tool_appid"[[:space:]]*"4185400"/d' "$manifest"
    echo "pocketds-steam-wrap-arm64-tools: wrapped ${dir##*/}" >&2
done
exit 0
