#!/usr/bin/env bash
# scripts/manual/kde-start-tethys.sh
#
# Manual: remote desktop recovery helper for tethys; not part of CI.
#
# Start/restart SDDM on tethys and set display geometry over :0.
# Intended for remote use after SSH-ing into tethys.
#
# Env overrides:
#   MODE=1920x1080   (preferred mode)
#   RATE=60          (refresh rate)
#   OUTPUTS="HDMI-1 DP-1" (space-separated outputs to try)
#   DISPLAY=:0       (X display; default :0)
#   XAUTHORITY=...   (override cookie; otherwise auto-detected from SDDM)

set -euo pipefail

MODE=${MODE:-1920x1080}
RATE=${RATE:-60}
OUTPUTS=${OUTPUTS:-"HDMI-1 DP-1"}
DISPLAY=${DISPLAY:-:0}

log() { printf "[kde-start] %s\n" "$*"; }

log "restarting sddm.service"
sudo systemctl restart sddm
sleep 2

# find SDDM Xauthority if not provided
if [[ -z "${XAUTHORITY:-}" ]]; then
  XAUTHORITY=$(ls /var/run/sddm/*/xauth_* 2>/dev/null | head -n1 || true)
fi

if [[ -z "${XAUTHORITY:-}" ]]; then
  log "warning: no XAUTHORITY found; xrandr may fail"
fi

# wait for X to come up
for attempt in {1..15}; do
  if DISPLAY=$DISPLAY XAUTHORITY=${XAUTHORITY:-} xrandr --query >/dev/null 2>&1; then
    break
  fi
  sleep 1
done

log "setting mode ${MODE}@${RATE} on outputs: ${OUTPUTS}"
for out in $OUTPUTS; do
  if DISPLAY=$DISPLAY XAUTHORITY=${XAUTHORITY:-} xrandr --output "$out" --mode "$MODE" --rate "$RATE" --primary >/dev/null 2>&1; then
    log "set $out to ${MODE}@${RATE}"
  else
    log "skip $out (xrandr failed)"
  fi
done

log "current xrandr:"
DISPLAY=$DISPLAY XAUTHORITY=${XAUTHORITY:-} xrandr --query || true

log "done."
