#!/usr/bin/env bash
# SPDX-License-Identifier: GPL-3.0-or-later
#
# pocketds-steam-install-proton — first-run-per-user installer for the
# Proton 11 ARM64 compatibility tool (the "Sildur build", originally
# from interfacinglinux.com and mirrored on archive.org).
#
# Drops two folders into ~/.local/share/Steam/compatibilitytools.d/:
#
#   Proton11ARM             — the Proton tree itself (custom build).
#   SteamLinuxRuntimeARM    — companion runtime Proton bind-mounts in.
#
# After this, Steam (restarted) shows "Proton 11.0 (ARM64, Local)" in
# game-properties → Compatibility, *and* the steamapps compatdata path
# stays portable across the system-wide updater.
#
# Wired up to a sdkarm64 symlink (Switchdeck does the same in
# launch-steam.sh) so $HOME/.steam/sdkarm64 → $STEAMROOT/linuxarm64,
# which Proton uses to find the bundled host arm64 SDK overlays.
#
# The tarball is ~1.09 GB; the SHA-1 is baked in below for integrity.
# Source URL is overridable via /etc/pocketds-steam/proton-url, which a
# user can point at a local mirror if they don't want to hammer
# archive.org on first boot.

set -euo pipefail

STEAMROOT="${HOME}/.local/share/Steam"
STEAMHOME="${HOME}/.steam"
COMPATDIR="${STEAMROOT}/compatibilitytools.d"
MARKER="${COMPATDIR}/.pocketds-proton11-arm64.done"

DEFAULT_PROTON_URL="https://archive.org/download/arm-64proton-runtime-64.tar/ARM64proton-Runtime64.tar.gz"
PROTON_SHA1="2249f787abd3aa0a2d4847aa17ebb225a8b3544a"
URL_OVERRIDE="/etc/pocketds-steam/proton-url"

if [ -r "${URL_OVERRIDE}" ]; then
    PROTON_URL="$(head -1 "${URL_OVERRIDE}" | tr -d '[:space:]')"
else
    PROTON_URL="${DEFAULT_PROTON_URL}"
fi

log() { printf 'pocketds-steam-install-proton: %s\n' "$*" >&2; }

if [ -e "${MARKER}" ]; then
    log "marker present (${MARKER}) — Proton 11 ARM64 already installed"
    exit 0
fi

# Bootstrap must have run first (we need $STEAMROOT to exist with the
# steamrtarm64 client unpacked). If it hasn't, retry on next login.
if [ ! -d "${STEAMROOT}/steamrtarm64" ]; then
    log "Steam bootstrap not yet complete — waiting for next login"
    exit 0
fi

mkdir -p "${COMPATDIR}"

# sdkarm64 symlink (Switchdeck does this in launch-steam.sh too; doing
# it here as well makes the install resilient to a user who launches
# Steam directly via $STEAMROOT/steamrtarm64/steam without ever going
# through launch-steam.sh).
ln -fsn "${STEAMROOT}/linuxarm64" "${STEAMHOME}/sdkarm64" 2>/dev/null || :

log "fetching Proton 11 ARM64 tarball (~1.09 GiB) from ${PROTON_URL}"
tmptar="$(mktemp -p "${COMPATDIR}" proton11arm64.XXXXXX.tar.gz)"
trap 'rm -f "${tmptar}"' EXIT
if ! wget -q --show-progress -c -t 5 -O "${tmptar}" "${PROTON_URL}"; then
    log "proton download failed — will retry on next login"
    exit 1
fi

# SHA-1 integrity check. archive.org publishes the same digest in
# files.xml (mtime 1776705588). Mismatch means a partial fetch or a
# substituted mirror; bail rather than ship a broken Proton.
actual_sha1="$(sha1sum "${tmptar}" | awk '{print $1}')"
if [ "${actual_sha1}" != "${PROTON_SHA1}" ]; then
    log "SHA-1 mismatch (got ${actual_sha1}, want ${PROTON_SHA1}) — aborting"
    exit 1
fi

# Extract under a temp subdir so a half-extracted tar doesn't half-
# populate compatibilitytools.d and confuse Steam.
stage="$(mktemp -d -p "${COMPATDIR}" .stage.XXXXXX)"
log "unpacking into ${stage}"
tar -xf "${tmptar}" -C "${stage}" --checkpoint=400 --checkpoint-action=dot

# The archive layout per interfacinglinux thread #1102 is two
# top-level folders: Proton11ARM and SteamLinuxRuntimeARM. Be permissive
# about exact names (some mirrors strip a leading "./", others tuck
# them under a wrapper dir) — find any directory that *looks* like a
# Proton or runtime install and move it up.
moved_any=0
while IFS= read -r -d '' candidate; do
    base="$(basename "${candidate}")"
    target="${COMPATDIR}/${base}"
    # Clean any prior partial install at the destination so the rename
    # always succeeds.
    rm -rf "${target}"
    mv "${candidate}" "${target}"
    log "installed ${base}"
    moved_any=1
done < <(find "${stage}" -maxdepth 3 -mindepth 1 -type d \
              \( -name 'Proton*' -o -name 'SteamLinuxRuntime*' \) -print0)

rm -rf "${stage}"

if [ "${moved_any}" -eq 0 ]; then
    log "no Proton*/SteamLinuxRuntime* dir found in archive — aborting"
    exit 1
fi

touch "${MARKER}"
log "Proton 11 ARM64 installed — restart Steam and pick 'Proton 11.0 (ARM64, Local)' in game properties → Compatibility"
