#!/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]   run it (the desktop menu entry)
#   bannerlator-steam-x64 --prepare                            install and set up, then exit
#   bannerlator-steam-x64 --exec ARGS...                       run the client binary with ARGS in
#                                                              its environment (bannerlator-session
#                                                              with BL_STEAM_CLIENT_ARCH=x86_64)
#
# 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, config and library, and never touches 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-r3
FEX_SHA256=cf3a87805ec51f8c42e197ff4883575e5bdec5247abe4c0beefb1796db358b5f
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"; }

x64_prepare() {
# --- 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).
# Each architecture's copy under the rootfs's own multiarch folder, named once through glibc's $LIB
# (lib/x86_64-linux-gnu or lib/i386-linux-gnu): every process loads the one built for it, so the
# 32-bit games get them too. A missing copy is skipped by the loader.
: > "$ROOTFS/etc/ld.so.preload"
for lib in libblsession libfakeinput; do
  have=0
  for arch in x86_64 i386; do
    [ -f "/usr/local/lib/$arch-linux-gnu/$lib.so" ] || continue
    mkdir -p "$ROOTFS/usr/local/lib/$arch-linux-gnu"
    cp -f "/usr/local/lib/$arch-linux-gnu/$lib.so" "$ROOTFS/usr/local/lib/$arch-linux-gnu/$lib.so"
    have=1
  done
  if [ "$have" = 1 ]; then echo "/usr/local/\$LIB/$lib.so" >> "$ROOTFS/etc/ld.so.preload"
  else step "warning: no x86 build of $lib (/usr/local/lib/x86_64-linux-gnu/$lib.so)"; fi
done
rm -f "$ROOTFS/usr/local/lib/libblsession-x86_64.so" "$ROOTFS/usr/local/lib/libfakeinput-x86_64.so"
# --- 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
# Its own library: the arm64 client's Windows installs are not what this client runs (it would
# switch a shared install to the Linux build and the arm64 client would download it again).
[ -L "$STEAM_X64/steamapps" ] && rm -f "$STEAM_X64/steamapps"
mkdir -p "$STEAM_X64/steamapps"
# They still enumerate /dev/dri, find the session's KGSL node there, and spin on it (x86 Turnip
# "failed to query kernel driver version", KMS dumb-buffer ioctls in a loop) - the webhelper never
# got a browser up. FEX looks in the rootfs first: an empty /dev/dri there hides the node.
mkdir -p "$ROOTFS/dev/dri"
# 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"
# 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"
fi
# The libraries the SteamRT container would give the client and the rootfs lacks (GTK 2 for
# steamui.so, ...): Valve's own platform runtime files, for what the rootfs does not have.
# They ship without their soname links (pressure-vessel makes those when it builds the container),
# so they are linked into a folder of our own and the rootfs's ldconfig adds the soname links there.
srt_libs=$X64_HOME/steamrt-libs
rm -rf "$srt_libs"
mkdir -p "$srt_libs"
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" ] || continue
  for f in "$d"/*.so*; do [ -e "$srt_libs/$(basename "$f")" ] || ln -s "$f" "$srt_libs/"; done
done
FEX_ROOTFS=$ROOTFS /usr/local/bin/FEX "$ROOTFS/usr/sbin/ldconfig.real" -n "$srt_libs" >>"$LOG" 2>&1 || step "ldconfig on $srt_libs failed"
# LD_LIBRARY_PATH beats the system folders whatever its order, so only what the rootfs lacks stays:
# the platform's own (older) glibc and the rest must not shadow the rootfs's.
for f in "$srt_libs"/*; do
  n=$(basename "$f")
  if [ -e "$ROOTFS/usr/lib/x86_64-linux-gnu/$n" ] || [ -e "$ROOTFS/lib/x86_64-linux-gnu/$n" ]; then rm -f "$f"; fi
done
  # Native Linux games: Steam runs them in the Steam Linux Runtime container (pressure-vessel), which
  # needs bwrap - no user namespaces here, as for the client. "DroidDeck direct" runs them with
  # Valve's scout library runtime instead, directly under FEX; the titles below are mapped to it.
  tool=$STEAM_X64/compatibilitytools.d/droiddeck-direct
  mkdir -p "$tool"
  cat > "$tool/compatibilitytool.vdf" <<'VDF'
"compatibilitytools"
{
  "compat_tools"
  {
    "droiddeck-direct"
    {
      "install_path" "."
      "display_name" "DroidDeck direct (no container)"
      "from_oslist" "linux"
      "to_oslist" "linux"
    }
  }
}
VDF
  cat > "$tool/toolmanifest.vdf" <<'VDF'
"manifest"
{
  "version" "2"
  "commandline" "/run %verb%"
}
VDF
  cat > "$tool/run" <<'RUN'
#!/bin/sh
# DroidDeck direct: a native Linux game with Valve's scout library runtime, no container.
verb=$1; shift
rt=$HOME/.local/share/Steam/ubuntu12_32/steam-runtime.old
[ -x "$rt/run.sh" ] || rt=$HOME/.local/share/Steam/ubuntu12_32/steam-runtime
case $verb in
  run|waitforexitandrun) exec "$rt/run.sh" "$@" ;;
  *) exec "$@" ;;
esac
RUN
  chmod 755 "$tool/run"
  # The mapping lives in config.vdf, which the client rewrites from memory as it exits: written
  # here, while no x86 client runs.
  if [ -f "$STEAM_X64/config/config.vdf" ] && ! pgrep -f 'steamrt64/steam( |$)' >/dev/null 2>&1; then
    python3 - "$STEAM_X64/config/config.vdf" ${BL_X64_DIRECT_APPS:-550} <<'PY' || step "could not map titles to DroidDeck direct"
import re, sys
path, apps = sys.argv[1], sys.argv[2:]
s = open(path, encoding="utf-8", errors="surrogateescape").read()

def block(text, key):
    """(start of the key, index after its opening brace, index of its closing brace) or None."""
    m = re.search(r'"%s"\s*\{' % re.escape(key), text)
    if not m:
        return None
    depth, k = 1, m.end()
    while depth:
        c = text[k]
        depth += c == "{"
        depth -= c == "}"
        k += 1
    return m.start(), m.end(), k - 1

if not block(s, "CompatToolMapping"):
    st = block(s, "Steam")
    if not st:
        sys.exit("no Steam section")
    s = s[:st[1]] + '\n\t\t\t\t"CompatToolMapping"\n\t\t\t\t{\n\t\t\t\t}' + s[st[1]:]
for app in apps:
    _, open_, close = block(s, "CompatToolMapping")
    inner = s[open_:close]
    old = block(inner, app)
    if old:
        inner = inner[:old[0]] + inner[old[2] + 1:]
    entry = ('\n\t\t\t\t\t"%s"\n\t\t\t\t\t{\n\t\t\t\t\t\t"name"\t\t"droiddeck-direct"\n'
             '\t\t\t\t\t\t"config"\t\t""\n\t\t\t\t\t\t"priority"\t\t"250"\n\t\t\t\t\t}' % app)
    s = s[:open_] + entry + inner + s[close:]
open(path, "w", encoding="utf-8", errors="surrogateescape").write(s)
PY
  fi
  # 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 while no x86 client
  # runs, so the next FEX starts one with this rootfs.
  if ! pgrep -f 'steamrt64/steam( |$)' >/dev/null 2>&1; then
    FEX_ROOTFS=$ROOTFS /usr/local/bin/FEXServer -k >/dev/null 2>&1 || true
  fi
}

# Whether the client draws on the GPU: FEX built with its host thunks (Vulkan and GL to the runtime's
# own drivers), unless BL_X64_SOFTWARE=1. Without them, software rendering (llvmpipe).
x64_gpu() {
  [ "${BL_X64_SOFTWARE:-0}" != 1 ] && [ -d /usr/local/share/fex-emu/GuestThunks ] && [ -d /usr/local/lib/fex-emu/HostThunks ]
}

# The environment the client and everything it starts run in.
x64_env() {
# 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
if x64_gpu; then
  # FEX's host thunks: the x86 program's libvulkan and libGL calls run in the runtime's own arm64
  # libraries - Turnip and Mesa on the GPU, with the session's settings for them (the Turnip ICD,
  # Zink and its tuning), as the arm64 client has them.
  printf '{"ThunksDB": {"GL": 1, "Vulkan": 1}}\n' > "$X64_HOME/thunks.json"
  export FEX_THUNKCONFIG=$X64_HOME/thunks.json
else
  # So are the desktop's GPU settings: zink over the arm64 Turnip ICD. x86 Mesa has no driver for
  # this GPU, so software: llvmpipe for GL (the client's own window needs GLX), and the rootfs's
  # own Vulkan ICDs (lavapipe) found by the x86 loader instead of the arm64 one.
  unset GALLIUM_DRIVER MESA_LOADER_DRIVER_OVERRIDE VK_ICD_FILENAMES VK_DRIVER_FILES LIBGL_KOPPER_DRI2 \
    ZINK_DEBUG ZINK_DESCRIPTORS TU_DEBUG MESA_NO_ERROR
  export LIBGL_ALWAYS_SOFTWARE=1 GALLIUM_DRIVER=llvmpipe
  # The X server hands out that node too (DRI3 open), and Mesa's software path then tries KMS dumb
  # buffers on it in a loop: present through plain X instead.
  export LIBGL_DRI3_DISABLE=1
fi
# The proot fast path (libblfastpath, preloaded into every guest process, FEX included) stands down
# by itself when FEX is about to run a 32-bit program (it broke FEX's 32-bit mode: SIGILL at start);
# 64-bit ones keep it. BL_X64_FP_OFF=1 turns it off for everything, as before.
[ "${BL_X64_FP_OFF:-0}" = 1 ] && export PROOT_FP_OFF=1
# FEX tuning: the app's default preset for games (core/FexPreset.kt PERFORMANCE_TSO, WinNative's
# default) - FEX's own defaults keep half-barrier TSO and full-precision x87, which cost every x86
# program time. A value already in the environment wins.
export FEX_TSOENABLED=${FEX_TSOENABLED:-1} FEX_VECTORTSOENABLED=${FEX_VECTORTSOENABLED:-0} \
  FEX_MEMCPYSETTSOENABLED=${FEX_MEMCPYSETTSOENABLED:-0} FEX_HALFBARRIERTSOENABLED=${FEX_HALFBARRIERTSOENABLED:-0} \
  FEX_X87REDUCEDPRECISION=${FEX_X87REDUCEDPRECISION:-1} FEX_MULTIBLOCK=${FEX_MULTIBLOCK:-1}
export HOME=$X64_HOME
# The session points these at the arm64 client's home; this client has its own.
export XDG_DATA_HOME=$X64_HOME/.local/share XDG_CONFIG_HOME=$X64_HOME/.config XDG_CACHE_HOME=$X64_HOME/.cache
export FEX_ROOTFS=$ROOTFS
export STEAM_EXTRA_COMPAT_TOOLS_PATHS=
# 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
[ -d "$X64_HOME/steamrt-shim" ] && export STEAM_RUNTIME_STEAMRT=$X64_HOME/steamrt-shim
# Not steamrt-shim/bin on PATH: with steam-runtime-launch-client found, the client hands a game
# to pressure-vessel's launcher service over the session bus, finds none and the game ends at once.
# Without it the client logs "Failed to wrap process item with launch client" and runs it itself.
export LD_LIBRARY_PATH=$STEAM_X64/steamrt64:$STEAM_X64/steamrt64/panorama:$X64_HOME/steamrt-libs
# 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
# proot is a tracer, so tier0 believes a debugger is attached and breaks into it with int3 on the
# first failed assertion: the web helper died of SIGTRAP a second after every start. The session
# shim hides the tracer from the x86 web helper too (preload/tracer.c).
export BL_WEBHELPER_HIDE_TRACER=1
}

# The client binary under FEX, for the session: the starting arguments, or -shutdown / a steam://
# URL handed to the running instance.
x64_exec() {
  x64_env
  cd "$STEAM_X64"
  exec "${BL_FEX:-/usr/local/bin/FEX}" "$STEAM_X64/steamrt64/steam" "$@"
}

case "${1:-}" in
  --prepare) x64_prepare; exit 0 ;;
  --exec) shift; x64_exec "$@" ;;
  --gpu) x64_gpu; exit $? ;;
esac

# --- standalone (the desktop menu entry) ------------------------------------------------------
# --- 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
x64_prepare
step "FEX, rootfs and client ready"
# BL_FEXSERVER_LOG: a FEXServer of our own in the foreground, logging there - every FEX process that
# logs to "server" (FEX_OUTPUTLOG, or an AppConfig) then has its lines tagged with its pid.
if [ -n "${BL_FEXSERVER_LOG:-}" ]; then
  FEX_ROOTFS=$ROOTFS "$(dirname "${BL_FEX:-/usr/local/bin/FEX}")/FEXServer" -f -p 600 >"$BL_FEXSERVER_LOG" 2>&1 &
  sleep 1
fi
# --- what bannerlator-session gives the arm64 client ---------------------------------------
# The client's connection header and Settings > Internet come from NetworkManager on the SYSTEM
# bus; without them it shows no connection while downloads run. Same bus config and stand-in as the
# session, started here when no system bus is up (a desktop has none), stopped with the client.
x64_bus= x64_nm= x64_pin=
x64_cleanup() {
  [ -n "$x64_pin" ] && kill "$x64_pin" 2>/dev/null
  [ -n "$x64_nm" ] && kill "$x64_nm" 2>/dev/null
  [ -n "$x64_bus" ] && kill "$x64_bus" 2>/dev/null
  return 0
}
trap x64_cleanup EXIT
if ! pgrep -f 'dbus-daemon --config-file=/usr/local/share/bannerlator/system-bus.conf' >/dev/null 2>&1 \
   && command -v dbus-daemon >/dev/null 2>&1 && command -v bannerlator-netmanager >/dev/null 2>&1; then
  mkdir -p /run/dbus /usr/local/share/bannerlator
  cat > /usr/local/share/bannerlator/system-bus.conf <<'BUSCONF'
<!DOCTYPE busconfig PUBLIC "-//freedesktop//DTD D-Bus Bus Configuration 1.0//EN"
 "http://www.freedesktop.org/standards/dbus/1.0/busconfig.dtd">
<busconfig>
  <type>system</type>
  <listen>unix:path=/run/dbus/system_bus_socket</listen>
  <auth>EXTERNAL</auth>
  <policy context="default">
    <allow user="*"/>
    <allow own="*"/>
    <allow send_destination="*"/>
    <allow receive_sender="*"/>
  </policy>
</busconfig>
BUSCONF
  rm -f /run/dbus/system_bus_socket
  dbus-daemon --config-file=/usr/local/share/bannerlator/system-bus.conf --nofork --nopidfile &
  x64_bus=$!
  for _ in $(seq 1 50); do [ -S /run/dbus/system_bus_socket ] && break; sleep 0.1; done
  if [ -S /run/dbus/system_bus_socket ]; then
    bannerlator-netmanager &
    x64_nm=$!
    step "network: system bus up, NetworkManager stand-in running"
  else
    step "network: the system bus did not come up; the client will show no connection"
  fi
fi
# What a killed client leaves behind: .crash opens the update UI on its spinner, stale htmlcache
# Singleton* locks can leave the UI blank (as in bannerlator-session).
if ! pgrep -f 'steamrt64/steam( |$)' >/dev/null 2>&1; then
  for f in "$STEAM_X64/.crash" "$STEAM_X64/steam.pid" "$STEAM_X64/config/htmlcache/SingletonLock" \
           "$STEAM_X64/config/htmlcache/SingletonCookie" "$STEAM_X64/config/htmlcache/SingletonSocket"; do
    { [ -e "$f" ] || [ -L "$f" ]; } && rm -f "$f"
  done
fi
# The session's CPU set for the client (BL_CLIENT_CPUS): Steam pins itself and its web helper to a
# few cores; re-pin every 5 s as the session does for the arm64 client.
if [ -n "${BL_CLIENT_CPUS:-}" ] && command -v taskset >/dev/null 2>&1; then
  (
    while sleep 5; do
      for pid in $(ps -A -o PID,ARGS | awk '$2=="FEX" && ($3 ~ /steamrt64\/steam$/ || $3 ~ /steamwebhelper$/) {print $1}'); do
        taskset -a -p -c "$BL_CLIENT_CPUS" "$pid" >/dev/null 2>&1
      done
    done
  ) &
  x64_pin=$!
fi
# BL_FEX: another FEX build for the client and everything it starts (a DEBUG_STRACE one, say).
# Restart on request (42, as steam.sh does), at most a few times.
for attempt in 1 2 3 4 5; do
  # The branch on disk must match -clientbeta before every start, or the client loops on rc=42.
  echo publicbeta > "$STEAM_X64/package/beta"
  step "starting the x86-64 SteamRT3 client under FEX (attempt $attempt): $*"
  rc=0
  if x64_gpu; then cef=(-cef-force-gpu -cef-ozone-platform=x11 -cef-use-gl=angle -cef-use-angle=vulkan); else cef=(-cef-disable-gpu); fi
  ( x64_exec -clientbeta publicbeta -no-cef-sandbox "${cef[@]}" "$@" ) >>"$LOG" 2>&1 || rc=$?
  step "client exited rc=$rc"
  [ "$rc" = 42 ] || break
done