#!/usr/bin/bash
set -e

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

is_kwin_running() {
    pgrep -f "kwin" > /dev/null
    return $?
}

is_mutter_running() {
    pgrep -f "mutter" > /dev/null
    return $?
}

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

CONF_FILE="/etc/lightdm/lightdm.conf.d/10-gamescope-session.conf"

session="${1:-gamescope}"

# Update session type
if [[ "$2" != "--root" ]]
    [[ $EUID == 0 ]] && die "Running $0 as root is not allowed"
    [[ -n ${HOME+x} ]] || die "No \$HOME variable"

    # Clear steam game desktop shortcut clutter
    DATA_HOME=${XDG_DATA_HOME:-$HOME/.local/share}
    grep --files-with-matches "Exec=steam steam://rungameid/" ${DATA_HOME}/applications/* | tr '\n' '\0' | xargs -0 -I {} rm {} || true

    if is_kwin_running; then
        qdbus6 org.kde.Shutdown /Shutdown org.kde.Shutdown.logout
    fi
    if is_mutter_running; then
        gnome-session-quit --no-prompt
    fi

    # Call the second script with root privileges
    exec pkexec "/usr/bin/steamos-session-select" "$session" --root
    exit 0
fi

LOCKFILE="/tmp/$(basename "$0").lock"

cleanup() {
    flock -u 200
    rm -f "$LOCKFILE"
}

exec 200>"$LOCKFILE"

# Try to acquire the lock
if ! flock -n 200; then
    echo "Another instance of the script is already running."
    exit 1
fi

trap cleanup EXIT INT TERM HUP ERR

session="${1:-gamescope}"
session_launcher="gamescope-session-steam"

# We use "plasma" as "desktop" to hook up to SteamOS's scripts
case "$session" in
    plasma-wayland-persistent)
        session_launcher="$desktop_session"
    ;;
    plasma-x11-persistent)
        session_launcher="$desktop_session"
    ;;
    desktop|plasma)
        session_launcher="${desktop_session}-session-oneshot"
    ;;
    gamescope)
        session_launcher="gamescope-session-steam"
    ;;
    *)
        echo >&2 "!! Unrecognized session '$session'"
        exit 1
    ;;
esac

echo "Updated user selected session to $session_launcher"

{
    echo "[Seat:*]"
    echo "autologin-session=$session_launcher"
} > "$CONF_FILE"

echo "Updated system autologin session to $session_launcher"
while is_kwin_running; do
    sleep 0.5
done
while is_mutter_running; do
    sleep 0.5
done
systemctl reset-failed display-manager.service
systemctl stop display-manager.service
sleep 1
systemctl start display-manager.service
echo "Restarted Display Manager"
