#!/bin/bash
# FWS — installe/actualise Proton-GE (GloriousEggroll) pour Steam :
# meilleure compatibilité des jeux Windows que le Proton officiel.
# S'exécute en UTILISATEUR (installe dans ~/.steam/root/compatibilitytools.d).
set -u
. /usr/local/lib/fws/i18n.sh proton common
say()  { printf '\n\033[1;34m==> %s\033[0m\n' "$*"; }
fail() { printf '\033[1;31m  ✗ %s\033[0m\n' "$*"; read -rp "$(t common.press_enter_to_close) " _; exit 1; }

[ "$(id -u)" -eq 0 ] && fail "$(t proton.not_as_root)"

API="https://api.github.com/repos/GloriousEggroll/proton-ge-custom/releases/latest"
DEST="$HOME/.steam/root/compatibilitytools.d"

say "$(t proton.looking_up_latest)"
JSON="$(curl -fsSL "$API")" || fail "$(t proton.github_unreachable)"
URL="$(printf '%s' "$JSON" | grep -o '"browser_download_url": *"[^"]*\.tar\.gz"' | cut -d'"' -f4 | head -1)"
SUM_URL="$(printf '%s' "$JSON" | grep -o '"browser_download_url": *"[^"]*\.sha512sum"' | cut -d'"' -f4 | head -1)"
[ -n "$URL" ] || fail "$(t proton.archive_not_found)"
NAME="$(basename "$URL" .tar.gz)"

if [ -d "$DEST/$NAME" ]; then
    say "$(t proton.already_installed name="$NAME")"
    read -rp "$(t common.press_enter_to_close) " _; exit 0
fi

TMP="$(mktemp -d)"
trap 'rm -rf "$TMP"' EXIT
say "$(t proton.downloading name="$NAME")"
curl -fL --progress-bar -o "$TMP/$NAME.tar.gz" "$URL" || fail "$(t proton.download_failed)"

if [ -n "$SUM_URL" ]; then
    say "$(t proton.verifying)"
    curl -fsSL -o "$TMP/sum" "$SUM_URL" \
        && (cd "$TMP" && sed "s|[^ ]*\.tar\.gz|$NAME.tar.gz|" sum | sha512sum -c -) \
        || fail "$(t proton.checksum_invalid)"
fi

say "$(t proton.installing_into folder="$DEST")"
mkdir -p "$DEST"
tar -xzf "$TMP/$NAME.tar.gz" -C "$DEST" || fail "$(t proton.extraction_failed)"

say "$(t proton.installed name="$NAME")"
# The texts carry their own line breaks: sed indents every line.
printf '%s\n' "$(t proton.how_to_enable name="$NAME")" "$(t proton.restart_steam)" | sed 's/^/  /'
read -rp "$(t common.press_enter_to_close) " _
