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

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

die() { echo >&2 "!! $*"; exit 1; }

# File this script will modify
CONF_FILE="/etc/sddm.conf.d/zz-steamos-autologin.conf"

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

log "Signaling session switch..."
touch "$HOME/.steamos-session-switch"

# It is possible to get things remaining from the previous session if SDDM is sigkilled by root systemd
# and our units are still running in the user systemd
systemctl --user stop gamescope-session.target
systemctl --user stop plasma-workspace.target
systemctl --user reset-failed

