#!/bin/bash
# EXPERIMENT, opt-in: Valve's x86-64 Linux Steam client under FEX, beside the default arm64 one.
#   bannerlator-steam-x64 [steam:// URL or client arguments]
#
# Why: the arm64 Linux client never runs VAC (TF2, L4D2: "Connection Blocked ... VAC secured
# server", no VAC line in any client log) - VAC modules are x86 code. The x86-64 client under FEX
# has a module it can run, the way SteamLite does in Wine. This runs Valve's client unchanged.
#
# Everything lives in its own home ($X64_HOME): the x86 client gets its own ~/.steam links, its
# own login and its own config, and never touches the arm64 client's. Games are shared: its
# steamapps is the arm64 client's. Only one client runs at a time (same account), so the arm64
# one is shut down first.
#
# First run downloads FEX (this repo's release), FEX's Ubuntu 24.04 x86 rootfs (~525 MB, unpacked
# ~1.5 GB) and the x86 client (~600 MB). Log: $X64_HOME/steam-x64.log.
set -eu
FEX_TAG=fex-2609-r2
FEX_SHA256=5c5fb5bfc2a78879fc4488d2b4cdea0d40d9268d9551bdc37c123e36da21b9c7
FEX_URL=https://github.com/Droid-Deck/DroidDeck/releases/download/$FEX_TAG/fex.tzst
ROOTFS_URL=https://rootfs.fex-emu.gg/Ubuntu_24_04/2026-08-11/Ubuntu_24_04.sqsh
CDN=https://client-update.fastly.steamstatic.com
MANIFEST=steam_client_publicbeta_ubuntu12

REAL_HOME=${HOME:-/root}
X64_HOME=${BL_X64_HOME:-$REAL_HOME/.droiddeck-x64}
ROOTFS=$X64_HOME/rootfs
STEAM_X64=$X64_HOME/.local/share/Steam
ARM_STEAM=${XDG_DATA_HOME:-$REAL_HOME/.local/share}/Steam
LOG=$X64_HOME/steam-x64.log
mkdir -p "$X64_HOME"
step() { echo "== $(date -u +%H:%M:%S) $*" | tee -a "$LOG"; }

# --- FEX -------------------------------------------------------------------------------------
if [ ! -x /usr/local/bin/FEX ] || [ "$(cat /usr/local/share/fex-emu/.droiddeck-tag 2>/dev/null)" != "$FEX_TAG" ]; then
  step "downloading FEX ($FEX_TAG)"
  tmp=$(mktemp -d)
  curl -fL --progress-bar "$FEX_URL" -o "$tmp/fex.tzst"
  if [ "$FEX_SHA256" != PENDING ]; then echo "$FEX_SHA256  $tmp/fex.tzst" | sha256sum -c --quiet; fi
  zstd -dc "$tmp/fex.tzst" | tar -C / -x
  rm -rf "$tmp"
  mkdir -p /usr/local/share/fex-emu && echo "$FEX_TAG" > /usr/local/share/fex-emu/.droiddeck-tag
fi
step "FEX ready ($FEX_TAG)"

# --- x86 rootfs --------------------------------------------------------------------------------
if [ ! -f "$ROOTFS/.droiddeck-complete" ]; then
  step "downloading FEX's Ubuntu 24.04 x86 rootfs"
  # Resumes a part-done download; a finished one answers 416, which is not a failure here.
  curl -fL --progress-bar -C - "$ROOTFS_URL" -o "$X64_HOME/rootfs.sqsh" || {
    rc=$?
    [ "$rc" = 22 ] && [ -s "$X64_HOME/rootfs.sqsh" ] || { step "rootfs download failed (curl $rc)"; exit 1; }
  }
  step "unpacking the rootfs"
  rm -rf "$ROOTFS"
  # Ownership and xattrs mean nothing in this guest; device nodes cannot be made here and are not
  # needed (FEX passes /dev through from the host).
  /usr/local/bin/unsquashfs -no-xattrs -no-progress -ignore-errors -d "$ROOTFS" "$X64_HOME/rootfs.sqsh" >>"$LOG" 2>&1 || true
  [ -x "$ROOTFS/usr/bin/bash" ] || { step "rootfs unpack failed (no usr/bin/bash); see $LOG"; exit 1; }
  rm -f "$X64_HOME/rootfs.sqsh"
  touch "$ROOTFS/.droiddeck-complete"
fi
# The rootfs's own ld.so.preload: a path missing from the rootfs falls through to the guest, whose
# list names the session's arm64 preloads. In it, the session shim built for x86-64 (System V IPC,
# which Android kernels lack: the client's tier0 gives up on start without its semaphore).
if [ -f /usr/local/lib/x86_64-linux-gnu/libblsession.so ]; then
  mkdir -p "$ROOTFS/usr/local/lib"
  cp -f /usr/local/lib/x86_64-linux-gnu/libblsession.so "$ROOTFS/usr/local/lib/libblsession-x86_64.so"
  echo /usr/local/lib/libblsession-x86_64.so > "$ROOTFS/etc/ld.so.preload"
else
  step "warning: no x86-64 session shim (/usr/local/lib/x86_64-linux-gnu/libblsession.so); the client will stop on semget"
  : > "$ROOTFS/etc/ld.so.preload"
fi

# --- the x86-64 client -------------------------------------------------------------------------
if [ ! -x "$STEAM_X64/steamrt64/steam" ] || [ ! -f "$STEAM_X64/package/droiddeck-installed" ]; then
  step "downloading the x86-64 Steam client ($MANIFEST)"
  work=$(mktemp -d)
  curl -fsSL "$CDN/$MANIFEST" -o "$work/manifest"
  version=$(awk -F'"' '$2 == "version" { print $4; exit }' "$work/manifest")
  # Same parsing as bannerlator-steam-install: every component block's plain zip and sha256.
  awk -F'"' '
    /^\t"/ && NF >= 3 && $4 == "" { block = $2 }
    $2 == "file" { file[block] = $4 }
    $2 == "sha2" { sha[block] = $4 }
    END { for (b in file) if (b ~ /_all$/ || b ~ /_ubuntu12$/) print b, file[b], sha[b] }
  ' "$work/manifest" | sort > "$work/parts"
  [ -s "$work/parts" ] || { step "no client components in $MANIFEST"; exit 1; }
  mkdir -p "$STEAM_X64/package"
  total=$(grep -c . "$work/parts")
  i=0
  while read -r block file sum; do
    i=$((i + 1))
    step "client: $block ($i/$total)"
    curl -fsSL "$CDN/$file" -o "$work/$file"
    echo "$sum  $work/$file" | sha256sum -c --quiet
    unzip -qo "$work/$file" -d "$STEAM_X64"
    rm -f "$work/$file"
  done < "$work/parts"
  rm -rf "$work"
  echo publicbeta > "$STEAM_X64/package/beta"
  echo "$version" > "$STEAM_X64/package/droiddeck-installed"
  chmod +x "$STEAM_X64/steam.sh" "$STEAM_X64/steamrt64/steam" "$STEAM_X64/ubuntu12_32/steam" 2>/dev/null || true
fi
# Shared games: the arm64 client's library, as long as it is not running at the same time.
if [ -d "$ARM_STEAM/steamapps" ] && [ ! -e "$STEAM_X64/steamapps" ]; then
  ln -s "$ARM_STEAM/steamapps" "$STEAM_X64/steamapps"
fi

# --- one client at a time ----------------------------------------------------------------------
if pgrep -f 'steamrtarm64/steam( |$)' >/dev/null 2>&1; then
  step "shutting down the arm64 client first"
  "$ARM_STEAM/steamrtarm64/steam" -shutdown >/dev/null 2>&1 || true
  for _ in $(seq 1 30); do pgrep -f 'steamrtarm64/steam( |$)' >/dev/null 2>&1 || break; sleep 1; done
fi

# --- run ---------------------------------------------------------------------------------------
# The arm64 session's library paths and preloads are aarch64 and mean nothing to x86 processes.
unset LD_LIBRARY_PATH LD_PRELOAD STEAM_RUNTIME STEAM_RUNTIME_PREFER_HOST_LIBRARIES
# The proot fast path (libblfastpath, preloaded into every guest process, FEX included) breaks
# FEX's 32-bit mode: every i386 program dies with SIGILL at start (FEX's own fatal trap), so
# Steam's 32-bit check reports libc.so.6 missing. 64-bit runs either way; proot then answers
# FEX's path calls itself.
export PROOT_FP_OFF=1
export HOME=$X64_HOME
export FEX_ROOTFS=$ROOTFS
# A FEX process takes its rootfs from FEXServer, not from its own environment, and a server
# started earlier without FEX_ROOTFS (any FEX run in this guest) answers with no rootfs at all:
# every x86 library lookup then falls through to the arm64 guest. Stop it, so the next FEX
# starts one with this rootfs.
/usr/local/bin/FEXServer -k >/dev/null 2>&1 || true
export STEAM_EXTRA_COMPAT_TOOLS_PATHS=
# What steam.sh sets up before it runs the client, for the x86 tree.
mkdir -p "$X64_HOME/.steam"
ln -sfn "$STEAM_X64" "$X64_HOME/.steam/root"
ln -sfn "$STEAM_X64" "$X64_HOME/.steam/steam"
ln -sfn "$STEAM_X64/ubuntu12_32" "$X64_HOME/.steam/bin32"
ln -sfn "$STEAM_X64/ubuntu12_64" "$X64_HOME/.steam/bin64"
ln -sfn "$STEAM_X64/linux32" "$X64_HOME/.steam/sdk32"
ln -sfn "$STEAM_X64/linux64" "$X64_HOME/.steam/sdk64"
# Valve's 64-bit SteamRT3 client (steamrt64/steam), the x86 twin of the arm64 one, started the way
# the session starts that one (bannerlator-session): directly, STEAM_RUNTIME=1, its own library
# folders first. Through steam.sh it would first run steam-runtime-check-requirements, whose
# bwrap probe needs user namespaces - proot has none. Software rendering: no x86 GPU driver.
export STEAM_RUNTIME=1
# Unlike the arm64 client, this one carries pressure-vessel (steamrt64/pv-runtime) and refuses to
# start when steam-runtime-check-requirements' bwrap probe cannot make a user namespace, which no
# Android app can. proot is the container here, as it is for the arm64 client, which has no such
# probe. STEAM_RUNTIME_STEAMRT names the runtime the client takes the probe from: Valve's own,
# linked file by file, with only the probe answering that the requirements are met.
srt_real=$STEAM_X64/steamrt64/pv-runtime/steam-runtime-steamrt
srt_shim=$X64_HOME/steamrt-shim
if [ -d "$srt_real" ]; then
  rm -rf "$srt_shim"
  mkdir -p "$srt_shim/bin"
  for e in "$srt_real"/* "$srt_real"/.[!.]*; do
    [ -e "$e" ] || continue
    [ "$(basename "$e")" = bin ] || ln -s "$e" "$srt_shim/$(basename "$e")"
  done
  for e in "$srt_real"/bin/*; do ln -s "$e" "$srt_shim/bin/$(basename "$e")"; done
  rm -f "$srt_shim/bin/steam-runtime-check-requirements"
  printf '#!/bin/sh
# bannerlator-steam-x64: proot stands in for user namespaces here.
exit 0
' > "$srt_shim/bin/steam-runtime-check-requirements"
  chmod 755 "$srt_shim/bin/steam-runtime-check-requirements"
  export STEAM_RUNTIME_STEAMRT=$srt_shim
fi
export LD_LIBRARY_PATH=$STEAM_X64/steamrt64:$STEAM_X64/steamrt64/panorama
# The libraries the SteamRT container would give the client and the rootfs lacks (GTK 2 for
# steamui.so, ...): Valve's own platform runtime files, last, so the rootfs's copies come first.
for d in "$STEAM_X64"/steamrt64/pv-runtime/steam-runtime-steamrt/steamrt3c_platform_*/files/lib/x86_64-linux-gnu \
         "$STEAM_X64"/steamrt64/pv-runtime/steam-runtime-steamrt/steamrt3c_platform_*/files/usr/lib/x86_64-linux-gnu; do
  [ -d "$d" ] && LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$d
done
# After an update the client re-executes itself inside the SteamRT container through
# pressure-vessel-wrap, which needs bwrap. The FEX rootfs with the client's own steamrt64 libraries
# is that container here; the client's recursion guard says it is already inside one.
export STEAM_STEAMRT_RECURSION_GUARD=1
cd "$STEAM_X64"
# Restart on request (42, as steam.sh does), at most a few times.
for attempt in 1 2 3 4 5; do
  step "starting the x86-64 SteamRT3 client under FEX (attempt $attempt): $*"
  rc=0
  /usr/local/bin/FEX "$STEAM_X64/steamrt64/steam" -clientbeta publicbeta -no-cef-sandbox \
    -cef-ozone-platform=x11 -cef-disable-gpu "$@" >>"$LOG" 2>&1 || rc=$?
  step "client exited rc=$rc"
  [ "$rc" = 42 ] || break
done
exit "$rc"
