#!/bin/bash
# Steam Game Mode entrypoint — uses saved credentials (zenity is unreliable in gamescope).
set -euo pipefail

HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
export SDL_VIDEO_MINIMIZE_ON_FOCUS_LOSS=0
export XDG_RUNTIME_DIR="${XDG_RUNTIME_DIR:-/run/user/$(id -u)}"
if [ -z "${DISPLAY:-}" ] || [ "${DISPLAY}" = ":1" ]; then
  export DISPLAY="${DISPLAY:-:0}"
fi
if [ -z "${XAUTHORITY:-}" ]; then
  for cand in /run/user/"$(id -u)"/xauth_* "$HOME/.Xauthority"; do
    [ -f "$cand" ] || continue
    export XAUTHORITY="$cand"
    break
  done
fi

# Resolve play.sh next to us (installed as ~/ffxi/bin/play-steam.sh)
PLAY="$HERE/play.sh"
if [ ! -x "$PLAY" ]; then
  PLAY="${DRIFTWOOD_ROOT:-$HOME/ffxi}/bin/play.sh"
fi

CFG="${XDG_CONFIG_HOME:-$HOME/.config}/driftwoodxi"
if [ -z "${DRIFTWOOD_USER:-}" ] && [ -f "$CFG/username" ]; then
  export DRIFTWOOD_USER="$(tr -d '\r\n' < "$CFG/username")"
fi
if [ -z "${DRIFTWOOD_PASS:-}" ]; then
  export DRIFTWOOD_PASS="$(secret-tool lookup service driftwoodxi account login 2>/dev/null || true)"
  if [ -z "${DRIFTWOOD_PASS}" ] && [ -f "$CFG/password" ]; then
    export DRIFTWOOD_PASS="$(tr -d '\r\n' < "$CFG/password")"
  fi
fi

if [ -z "${DRIFTWOOD_USER:-}" ] || [ -z "${DRIFTWOOD_PASS:-}" ]; then
  if [ -n "${DISPLAY:-}" ] && command -v zenity >/dev/null; then
    exec "$PLAY"
  fi
  echo "No saved DriftwoodXI login. In Desktop Mode run play.sh once and choose Remember." >&2
  exit 1
fi

export DRIFTWOOD_USER DRIFTWOOD_PASS
export DRIFTWOOD_SKIP_CONFIRM=1
exec "$PLAY"
