#!/bin/bash

# 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 graphical-session-pre.target
systemctl --user reset-failed

# Update the enviroment with DESKTOP_SESSION and all XDG variables
dbus-update-activation-environment --systemd DESKTOP_SESSION `env | grep ^XDG_ | cut -d = -f 1`

# This makes it so that xdg-desktop-portal only looks for holo- and
# gamescope-specific portal implementations and doesn't try to start other
# irrelevant portal implementations (gtk, kde, …).
# Plasma resets this variable when it starts.
systemctl --user set-environment XDG_DESKTOP_PORTAL_DIR=""

# If this shell script is killed then stop gamescope-session
trap 'systemctl --user stop gamescope-session.target' HUP INT TERM

# Start gamescope-session and wait
systemctl --user --wait start gamescope-session.target &
wait
logger Gamescope Session Ended - Performing Final Cleanup

# The 'wait' above blocks until gamescope-session.target stops
# We want to wait until *everything* has finished. We know systemd will have
# queued a stop job on graphical-session-pre aleady
# by also queuing up a job we can block until that completes
systemctl --user stop graphical-session-pre.target
logger Gamescope Session Ended - Cleanup Complete
