#!/bin/sh
# Launches Steam in Big Picture (gamepad UI). Installed to /usr/local/bin/steam-big-picture.
#
# This is the image's default application: the sway config execs steam-session, which
# execs this, and this is what the TV shows within a few seconds of power-on. Nothing
# else is running at that point — see media-session for why.
#
# GAMESCOPE
# ---------
# When gamescope is present (0300-steam.hook.chroot installs it if the release has it)
# Steam runs nested inside it. That is what Valve ships on the Deck and it buys three
# things that matter on a television: a fixed output resolution and refresh rate that a
# game cannot change out from under the compositor, integer/FSR scaling so a 1080p game
# on a 4K set is sharp rather than smeared, and a framerate limiter. Without gamescope
# Steam runs directly on Xwayland — fully functional, just without those.
#
# IDEMPOTENT: relaunching while Steam is already up focuses the existing client instead
# of starting a second one (Steam would refuse anyway, but noisily, and the second
# process would sit in the session doing nothing). This is what makes the HA "Launch
# Steam" button and the remote's own key safe to press repeatedly.
set -eu

WS_STEAM="1:steam"

if ! command -v steam >/dev/null 2>&1; then
  echo "steam-big-picture: Steam is not installed on this image — see" >&2
  echo "  live-build/config/hooks/normal/0300-steam.hook.chroot, which logs why." >&2
  exit 1
fi

# Already running: switch to it and focus rather than starting another client.
if pgrep -u "$(id -u)" -x steam >/dev/null 2>&1; then
  swaymsg workspace "$WS_STEAM" >/dev/null 2>&1 || true
  swaymsg '[class="^[Ss]team$"] focus' >/dev/null 2>&1 || true
  # Steam's own URL handler is the documented way to ask a *running* client to go back
  # into Big Picture; there is no command-line flag that does it to an existing process.
  exec steam steam://open/bigpicture
fi

# -gamepadui is the current Big Picture. -tenfoot is the old one and is gone; if this
# ever stops opening the gamepad UI, that flag name is the first thing to check against
# the installed client (`steam -help`).
STEAM_ARGS="-gamepadui -nochatui -nofriendsui"

if command -v gamescope >/dev/null 2>&1 && [ "${STEAMTV_USE_GAMESCOPE:-auto}" != "false" ]; then
  # -f  fullscreen, -e  Steam integration (lets Steam drive resolution per game),
  # --adaptive-sync  hands VRR through to a set that supports it.
  # Output geometry is deliberately NOT pinned here: gamescope defaults to the
  # connected display's native mode, and hardcoding 1920x1080 would be wrong on the 4K
  # set this is most likely plugged into. Pin it in STEAMTV_GAMESCOPE_ARGS if a
  # specific title needs it.
  # shellcheck disable=SC2086
  exec gamescope -f -e --adaptive-sync ${STEAMTV_GAMESCOPE_ARGS:-} -- steam $STEAM_ARGS
fi

# shellcheck disable=SC2086
exec steam $STEAM_ARGS
