#!/bin/bash
set -euo pipefail
LOGFILE="$HOME/.local/logs/session.log"

log() { echo "[$(date --iso-8601=seconds)] $*" | tee -a "$LOGFILE"; }

session="${1:-gamescope}"

case "$session" in
  plasma*)
    log "Plasma session selected."
    touch "$HOME/.desktop-session-plasma"
  ;;
  gamescope)
    log "Gamescope session selected."
    if [[ -f "$HOME/.desktop-session-plasma" ]]; then
      rm "$HOME/.desktop-session-plasma"
    fi
  ;;
  *)
    log "!! Unrecognized session '$session'"
    exit 1
  ;;
esac

if systemctl --user is-active --quiet sunshine.scope; then
  log "Stopping sunshine.scope"
  systemctl --user stop sunshine.scope
fi
if systemctl --user is-active --quiet steam.scope; then
  log "Stopping steam.scope"
  systemctl --user stop steam.scope
fi
if systemctl --user is-active --quiet plasma.scope; then
  log "Stopping plasma.scope"
  systemctl --user stop plasma.scope
fi
sleep 5
log "Restarting graphical session service..."
systemctl --user restart session.service