#!/usr/bin/env bash
# "forever and forever and forever": keep game + capture alive, restart on death.
set -u
BASE=/home/ubuntu/tf2stream
source "$BASE/stream.env"
export DISPLAY=":${DISPLAY_NUM}"
LOG="$BASE/logs/supervisor.log"

log(){ echo "[$(cat /proc/uptime | cut -d' ' -f1)s] $*" | tee -a "$LOG"; }

cleanup(){ log "shutting down"; kill "${GAME_PID:-0}" "${CAP_PID:-0}" 2>/dev/null; exit 0; }
trap cleanup INT TERM

while true; do
  log "starting TF2..."
  bash "$BASE/run_game.sh" & GAME_PID=$!

  # wait for the game to actually render before we start grabbing.
  # (llvmpipe cold-start of 2fort can take a while.)
  sleep 45

  if ! kill -0 "$GAME_PID" 2>/dev/null; then
    log "game died during boot; see logs/tf2.log; retrying in 10s"
    sleep 10; continue
  fi

  log "starting capture -> YouTube..."
  bash "$BASE/run_capture.sh" & CAP_PID=$!

  # supervise: if either dies, tear both down and loop.
  while kill -0 "$GAME_PID" 2>/dev/null && kill -0 "$CAP_PID" 2>/dev/null; do
    sleep 15
  done

  log "a component exited (game=$(kill -0 $GAME_PID 2>/dev/null && echo up || echo DOWN) cap=$(kill -0 $CAP_PID 2>/dev/null && echo up || echo DOWN)); restarting cycle"
  kill "$GAME_PID" "$CAP_PID" 2>/dev/null
  sleep 8
done
