#!/usr/bin/env bash
# Launch Xvfb + TF2 client listen server on 2fort with bots.
# Software-render path: TF2(D3D9) -> DXVK -> lavapipe(Vulkan) -> llvmpipe(GL).
set -u
BASE=/home/ubuntu/tf2stream
source "$BASE/stream.env"
export DISPLAY=":${DISPLAY_NUM}"
RW="${RENDER_WIDTH:-640}"; RH="${RENDER_HEIGHT:-480}"

# 1) private virtual display at RENDER resolution
if ! xdpyinfo -display "$DISPLAY" >/dev/null 2>&1; then
  setsid Xvfb "$DISPLAY" -screen 0 "${RW}x${RH}x24" -nolisten tcp >"$BASE/logs/xvfb.log" 2>&1 < /dev/null &
  sleep 2
fi

# 2) install our cfgs into the game tree
cp -f "$BASE/cfg/autoexec.cfg"   "$BASE/tf2/tf/cfg/autoexec.cfg"
cp -f "$BASE/cfg/server.cfg"     "$BASE/tf2/tf/cfg/server.cfg"
cp -f "$BASE/cfg/ctf_2fort.cfg"  "$BASE/tf2/tf/cfg/ctf_2fort.cfg"

# 3) PERSISTENT shader caches -> the expensive first-launch DXVK compile happens
#    once, ever. Subsequent (re)starts reuse it and reach first-frame fast.
mkdir -p "$BASE/cache/dxvk" "$BASE/cache/mesa"
export DXVK_STATE_CACHE=1
export DXVK_STATE_CACHE_PATH="$BASE/cache/dxvk"
export MESA_SHADER_CACHE_DIR="$BASE/cache/mesa"
export MESA_SHADER_CACHE_MAX_SIZE=2G
export __GL_SHADER_DISK_CACHE=1

# 4) DXVK: use graphics-pipeline-library (render while compiling => less black stall)
export DXVK_CONFIG="dxvk.enableGraphicsPipelineLibrary = True; dxgi.maxFrameLatency = 1"

# 5) software GL/Vulkan + misc
export LIBGL_ALWAYS_SOFTWARE=1
export GALLIUM_DRIVER=llvmpipe
export MESA_GL_VERSION_OVERRIDE=4.5
export __GL_SYNC_TO_VBLANK=0
export FONTCONFIG_PATH=/etc/fonts
export SteamAppId=440 SteamGameId=440

cd "$BASE/tf2"
echo 440 > "$BASE/tf2/steam_appid.txt"

# -dxlevel 90 = minimal shader set (far fewer DXVK pipelines to compile).
# Rendered at RENDER res; capture upscales to stream res.
exec "$BASE/sniper/run-in-sniper" -- env \
  DISPLAY="$DISPLAY" SteamAppId=440 SteamGameId=440 FONTCONFIG_PATH=/etc/fonts \
  DXVK_STATE_CACHE=1 DXVK_STATE_CACHE_PATH="$BASE/cache/dxvk" \
  MESA_SHADER_CACHE_DIR="$BASE/cache/mesa" MESA_SHADER_CACHE_MAX_SIZE=2G \
  DXVK_CONFIG="$DXVK_CONFIG" \
  ./tf.sh -game tf -steam -insecure \
  -novid -nostartupsound -nojoy -nosteamcontroller -nohltv \
  -dxlevel 90 \
  -w "$RW" -h "$RH" -sw -noborder \
  +sv_lan 1 +sv_cheats 1 +maxplayers 12 \
  -condebug \
  +exec autoexec \
  +map ctf_2fort \
  >"$BASE/logs/tf2.log" 2>&1
