#!/usr/bin/bash
# Switch between Game Mode and Desktop Mode (SDDM autologin based, like SteamOS).
#
#   steamos-session-select [gamescope|plasma|desktop|plasma-persistent] [--no-logout]
#
# The SDDM autologin session is changed through a small root helper (pkexec,
# allowed without password for the active local session) and then the current
# graphical session is ended. SDDM is configured with Relogin=true, so it logs
# straight back in, into the newly selected session.
set -euo pipefail

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

session="${1:-gamescope}"
case "$session" in
    gamescope)
        target="gamescope-session-steam.desktop" ;;
    plasma|desktop)
        target="plasmawayland-session-oneshot.desktop" ;;
    plasma-persistent|plasma-wayland-persistent|plasma-x11-persistent)
        target="plasmawayland.desktop" ;;
    *)
        die "Unrecognised session '$session'" ;;
esac

[[ $EUID -ne 0 ]] || die "Run this script as your user, not root."

pkexec /usr/bin/steamos-polkit-helpers/steamos-set-autologin "$target" \
    || die "Could not change the autologin session"

[[ "${2:-}" == "--no-logout" ]] && exit 0

# remove Steam game shortcuts left on the desktop
DATA_HOME=${XDG_DATA_HOME:-"$HOME/.local/share"}
grep -l "Exec=steam steam://rungameid/" "$DATA_HOME"/applications/* 2>/dev/null \
    | xargs -r rm -- || true

# end the current session, SDDM relogs into the new one
if pgrep -u "$UID" -x kwin_wayland >/dev/null || pgrep -u "$UID" -x kwin_x11 >/dev/null; then
    dbus-send --session --type=method_call --print-reply --dest=org.kde.Shutdown \
            /Shutdown org.kde.Shutdown.logout >/dev/null 2>&1 \
        || qdbus6 org.kde.Shutdown /Shutdown org.kde.Shutdown.logout 2>/dev/null \
        || { [[ -n "${XDG_SESSION_ID:-}" ]] && loginctl terminate-session "$XDG_SESSION_ID"; }
elif pgrep -u "$UID" -x gamescope >/dev/null || pgrep -u "$UID" -f gamescope-session >/dev/null; then
    # leaving Game Mode: closing Steam ends gamescope-session-plus
    steam -shutdown >/dev/null 2>&1 || true
    if [[ -n "${XDG_SESSION_ID:-}" ]]; then
        ( sleep 20; loginctl terminate-session "$XDG_SESSION_ID" ) >/dev/null 2>&1 &
    fi
elif [[ -n "${XDG_SESSION_ID:-}" ]]; then
    loginctl terminate-session "$XDG_SESSION_ID"
fi
