#!/usr/bin/env bash
# SPDX-License-Identifier: GPL-3.0-or-later
#
# pocketds-steam-install-runtime — keep a private copy of Steam Linux
# Runtime 4.0 - Arm64 for the ARM64 Protons.
#
# Steam's own copy (appid 4185400) is served as an empty depot to this
# client: each "verify" deletes _v2-entry-point and the rest, and the
# library shows it installable at 0 B. Valve publishes the same runtime
# as an image, so fetch the stable one, check it against SHA256SUMS and
# unpack it outside steamapps, where Steam never touches it.
# /usr/libexec/pocketds-steam/arm64-proton prefers Steam's copy when it is
# complete and falls back to this one.
#
# Runs at every login; it only downloads when the stable version changes.

set -euo pipefail

BASE="https://repo.steampowered.com/steamrt4/images/latest-public-stable"
IMAGE="SteamLinuxRuntime_4-arm64"
DEST_ROOT="${XDG_DATA_HOME:-${HOME}/.local/share}/pocketds-steam"
DEST="${DEST_ROOT}/${IMAGE}"

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

if ! version="$(wget -qO- -t 3 -T 30 "${BASE}/VERSION.txt" | tr -d '[:space:]')" || [ -z "${version}" ]; then
    log "cannot reach ${BASE} — keeping the current runtime"
    exit 0
fi
if [ -x "${DEST}/_v2-entry-point" ] && [ "$(cat "${DEST}/.pocketds-version" 2>/dev/null)" = "${version}" ]; then
    log "runtime ${version} already installed"
    exit 0
fi

mkdir -p "${DEST_ROOT}"
work="$(mktemp -d -p "${DEST_ROOT}" .runtime.XXXXXX)"
trap 'rm -rf "${work}"' EXIT

log "fetching ${IMAGE} ${version}"
wget -q -t 5 -T 60 -O "${work}/${IMAGE}.tar.xz" "${BASE}/${IMAGE}.tar.xz"
wget -q -t 3 -T 30 -O "${work}/SHA256SUMS" "${BASE}/SHA256SUMS"
want="$(sed -n "s/^\([0-9a-f]\{64\}\) \*\{0,1\}${IMAGE}\.tar\.xz$/\1/p" "${work}/SHA256SUMS")"
got="$(sha256sum "${work}/${IMAGE}.tar.xz" | cut -d' ' -f1)"
if [ -z "${want}" ] || [ "${want}" != "${got}" ]; then
    log "SHA-256 mismatch (got ${got}, want ${want:-none}) — aborting"
    exit 1
fi

tar -xf "${work}/${IMAGE}.tar.xz" -C "${work}"
if [ ! -x "${work}/${IMAGE}/_v2-entry-point" ]; then
    log "archive has no ${IMAGE}/_v2-entry-point — aborting"
    exit 1
fi
echo "${version}" > "${work}/${IMAGE}/.pocketds-version"

rm -rf "${DEST}.old"
[ -e "${DEST}" ] && mv "${DEST}" "${DEST}.old"
mv "${work}/${IMAGE}" "${DEST}"
rm -rf "${DEST}.old"
log "installed ${IMAGE} ${version}"
