#!/usr/bin/bash
set -euo pipefail

session_conf="/etc/trup/session.conf";  . "$session_conf"

###############################################################################
# helpers
###############################################################################
is_kwin_running()   { pgrep -f kwin   >/dev/null 2>&1 || return 1; }
is_mutter_running() { pgrep -f mutter >/dev/null 2>&1 || return 1; }

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

###############################################################################
# constants / globals
###############################################################################
SESSION_CONF_FILE="/etc/lightdm/lightdm.conf.d/10-gamescope-session.conf"
USER_CONF_FILE="/etc/lightdm/lightdm.conf.d/00-autologin-user.conf"
LOCKFILE="/tmp/$(basename "$0").$UID.lock"

session="${1:-gamescope}"

###############################################################################
# phase 1 – run as *user* (do NOT allow sudo)
###############################################################################
if [[ "${2:-}" != "--root" ]]; then
    [[ $EUID -eq 0 ]] && die "Run this script as your user, not root."
    [[ -n ${HOME:-}    ]] || die "\$HOME not set"

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

    # politely ask the current compositor to log out
    is_kwin_running   && qdbus6 org.kde.Shutdown /Shutdown org.kde.Shutdown.logout
    is_mutter_running && gnome-session-quit --no-prompt

    exec pkexec "$0" "$session" --root   # re‑run as root
fi

###############################################################################
# phase 2 – run as *root*
###############################################################################
# locking
cleanup() { rm -f "$LOCKFILE"; }
exec 200>"$LOCKFILE"
flock -n 200 || die "Another instance is already running."
trap cleanup EXIT INT TERM HUP

# map session → launcher
case "$session" in
  plasma-wayland-persistent|plasma-x11-persistent) session_launcher="$desktop_session" ;;
  desktop|plasma)                                 session_launcher="${desktop_session}-session-oneshot" ;;
  gamescope)                                      session_launcher="gamescope-session-steam" ;;
  *) die "Unrecognised session '$session'" ;;
esac
echo "Selected session launcher: $session_launcher"

# wait until the old compositor is really gone
while is_kwin_running   ; do sleep 0.5; done
while is_mutter_running ; do sleep 0.5; done

###############################################################################
# restart Display Manager – loop until it comes up, toggling the session each
# time it fails (gamescope <-> desktop)
###############################################################################
restart_dm() {
    systemctl reset-failed display-manager.service || true
    systemctl restart display-manager.service || true
}

start_and_wait() {
    restart_dm                     # stop → start DM
    sleep 3                        # give it 3 s to come up

    if systemctl is-active --quiet display-manager.service; then
        return 0                  # DM is active → success
    else
        return 1                  # DM not active → failure
    fi
}

# build the two launcher names (gamescope  <->  desktop)
gamescope_launcher="gamescope-session-steam"
desktop_launcher="${desktop_session}-session-oneshot"

# decide which one we start with
current_launcher="$session_launcher"         # set earlier in the script

for ((attempt=1; ; attempt++)); do
    printf '[Seat:*]\nautologin-session=%s\n' "$current_launcher" > "$SESSION_CONF_FILE"
    printf '[Seat:*]\nautologin-user=deck\n' > "$USER_CONF_FILE"
    echo "Attempt $attempt: starting Display Manager with $current_launcher"

    if start_and_wait; then
        echo "Display Manager is active with $current_launcher (after $attempt attempt(s))"
        session_launcher="$current_launcher"   # final session that succeeded
        break
    fi

    echo "Display Manager failed with $current_launcher"

    # toggle launcher for next iteration
    if [[ "$current_launcher" == "$gamescope_launcher" ]]; then
        current_launcher="$desktop_launcher"
    else
        current_launcher="$gamescope_launcher"
    fi
done
