#!/bin/sh
# The session's first and normally only process. Installed to /usr/local/bin/steam-session.
#
# THIS IS THE "MEDIA APPS ONLY START WHEN YOU LEAVE BIG PICTURE" MECHANISM, HALF ONE.
#
# The box boots to Steam and nothing else: no browser, no Spotify, no player. Those are
# started the first time somebody actually leaves Big Picture. Two independent triggers
# do that, because there are two different ways to leave and neither one can see the
# other:
#
#   1. THIS SCRIPT — "Exit Steam" / the client crashing. steam-big-picture runs in the
#      foreground, so when the Steam client goes away this script resumes on the line
#      after it and brings the media session up, focused.
#   2. /usr/local/bin/session-watcher — "Exit Big Picture mode", alt-tabbing, the
#      remote's channel keys, or the HA workspace select. Steam is still running, so
#      trigger 1 never fires; what changes is the focused sway workspace, which the
#      watcher subscribes to.
#
# Both call `media-session start`, which is idempotent, so whichever fires first wins
# and the second is a no-op. That is the whole design — no window-title matching, no
# polling for Big Picture's internal state, nothing that breaks when Valve reshuffles
# the UI. See media-session for the guards that make double-firing free.
#
# WHY THIS IS NOT A LOOP: if Steam exits, it stays exited. Relaunching it automatically
# would make "Exit Steam" impossible to act on from the sofa, and the box would never
# be usable as anything but a games console. Getting back in is a button (HA, the
# remote's Home key, or $mod+s) — see the sway config.
set -eu

# Register Prism Launcher as a non-Steam game BEFORE Steam starts. Ordering is not
# incidental: Steam reads shortcuts.vdf at startup and rewrites it from memory when it
# exits, so anything written while it is running is silently discarded. This is also
# why the registration lives here rather than in an `exec_always` in the sway config,
# where it would race the client. Idempotent, and a no-op until somebody has logged
# into Steam on this machine — see the script's own header for why it cannot be baked
# into the image.
/usr/local/bin/steam-shortcut-prism || \
  echo "steam-session: could not register the Prism shortcut; Prism will still launch," \
       "just without Steam Input"

/usr/local/bin/steam-big-picture || \
  echo "steam-session: Steam exited non-zero; falling through to the media session anyway"

# --focus because this path means the screen is now showing nothing at all: Steam has
# quit and the user is looking at an empty compositor. The watcher's path deliberately
# does not focus, since there the user already chose where to be.
exec /usr/local/bin/media-session start --focus
