#!/usr/bin/sh

declare -r CLIENT=$1

# Run these as user only
if [[ $EUID != 0 ]]; then
# Script to start the session used by Valve with minor tweaks for ChimeraOS.

# Window managers sets this to wayland but apps using Gamescope must use x11
export XDG_SESSION_TYPE=x11

# 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 doesn't find any portal implementations and doesn't start them and makes
# them crash/exit because the dbus env has no DISPLAY. In turn this causes dbus calls to the portal which don't rely
# on implementations to hang (such as SDL talking to the real time portal)
systemctl --user set-environment XDG_DESKTOP_PORTAL_DIR=""

# Remove these as they prevent gamescope-session-plus from starting correctly
systemctl --user unset-environment DISPLAY XAUTHORITY

# If this shell script is killed then stop gamescope-session-plus
trap "systemctl --user stop gamescope-session-plus@${CLIENT}.service" HUP INT TERM

# Start gamescope-session-plus and wait
systemctl --user --wait start gamescope-session-plus@${CLIENT}.service &
wait

# Unset XDG_DESKTOP_PORTAL_DIR environment to allow desktop portals to work
# again.
systemctl --user unset-environment XDG_DESKTOP_PORTAL_DIR
fi

# Become root so we can restart desktop managers
if [[ $EUID != 0 ]]; then
  exec pkexec "$(realpath $0)"
  exit 1
fi

# Stop Deckyloader
systemctl stop plugin_loader.service

# GNOME/GDM
if [[ ! -z $(systemctl status gdm | grep running) ]]; then
  # gdm needs reload + TimedLogin instead of full restart
  # full restart will fail
  systemctl reload gdm
fi
# KDE/plasmalogin
if [[ ! -z $(systemctl status plasmalogin | grep running) ]]; then
  systemctl restart plasmalogin
fi
# LightDM (For Chimera)
if [[ ! -z $(systemctl status lightdm | grep running) ]]; then
  systemctl restart lightdm
fi
