#!/usr/bin/env bash
# SPDX-License-Identifier: GPL-3.0-or-later
#
# steamos-session-select — switch the Pocket DS between gaming
# (gamescope + Steam Big Picture) and desktop (Plasma) modes.
#
# Named to match the command Steam's gamepad UI invokes from its power
# menu ("Switch to Desktop"): Steam runs `steamos-session-select
# desktop`. The desktop side ships a "Return to Gaming Mode" launcher
# that runs `steamos-session-select gaming`.
#
# The choice is a per-user marker read by pocketds-gamescope-session
# (the autologin session Exec) on the next login. After writing it we
# log the current session out so the display manager re-runs the
# dispatcher, which honours the new selection. Sticky, like SteamOS:
# the mode persists across reboots until switched again — except for the
# plain `plasma` selection Steam's "Switch to Desktop" sends, which (as on
# SteamOS) lasts one session and then falls back to gaming.

set -u

STATE_DIR="${XDG_STATE_HOME:-$HOME/.local/state}/pocketds-steam"
SEL_FILE="$STATE_DIR/session"

usage() { echo "usage: ${0##*/} {gaming|desktop}" >&2; exit 2; }

case "${1:-gaming}" in
    gaming|gamescope|steam|game)            choice="gaming" ;;
    plasma|plasma-wayland|plasma-x11)       choice="desktop-once" ;;
    desktop|kde|plasma*-persistent)         choice="desktop" ;;
    -h|--help)                              usage ;;
    *)                                      usage ;;
esac

mkdir -p "$STATE_DIR" 2>/dev/null || :
printf '%s\n' "$choice" > "$SEL_FILE"

# Log out of the running session so autologin re-dispatches. Prefer the
# clean Plasma logout D-Bus call (present in desktop mode); fall back to
# tearing down the whole user session (works from inside gamescope,
# which has no Plasma shell to talk to).
if pgrep -u "$USER" -x ksmserver >/dev/null 2>&1 && \
   busctl --user call org.kde.Shutdown /Shutdown org.kde.Shutdown logout >/dev/null 2>&1; then
    exit 0
fi
if command -v loginctl >/dev/null 2>&1 && \
   loginctl terminate-user "$USER" >/dev/null 2>&1; then
    exit 0
fi
# Last resort: kill the process group's session leader chain.
systemctl --user exit >/dev/null 2>&1 || kill -TERM -1 2>/dev/null || :
