#!/bin/bash

##
## Session globals
##
export SDL_VIDEO_MINIMIZE_ON_FOCUS_LOSS=0

export HOMETEST_DESKTOP=1
export HOMETEST_DESKTOP_SESSION=plasma

export STEAM_USE_MANGOAPP=1
export MANGOHUD_CONFIGFILE=$HOME/.local/share/Steam/config/mangohud.conf

# Initially write no_display to our config file
# so we don't get mangoapp showing up before Steam initializes
# on OOBE and stuff.
mkdir -p $(dirname "$MANGOHUD_CONFIGFILE")
echo "no_display" > "$MANGOHUD_CONFIGFILE"

# Let's try this across the board to see if it breaks anything
# Helps performance in HZD, Cyberpunk, at least
# Expose 8 physical cores, instead of 4c/8t
export WINE_CPU_TOPOLOGY=8:0,1,2,3,4,5,6,7

# To expose vram info from radv's patch we're including
export WINEDLLOVERRIDES=dxgi=n

# Workaround for steam getting killed immediatly during reboot
# See: jupiter/tasks/-/issues/280
export STEAMOS_STEAM_REBOOT_SENTINEL="/tmp/steamos-reboot-sentinel"
if [[ -e "$STEAMOS_STEAM_REBOOT_SENTINEL" ]]; then
	rm -f "$STEAMOS_STEAM_REBOOT_SENTINEL"
	sudo reboot
fi

# Enable volume key management via steam for this session
export STEAM_ENABLE_VOLUME_HANDLER=1

# Have SteamRT's xdg-open send http:// and https:// URLs to Steam
export SRT_URLOPEN_PREFER_STEAM=1

# Disable automatic audio device switching in steam, now handled by wireplumber
export STEAM_DISABLE_AUDIO_DEVICE_SWITCHING=1

# Enable support for xwayland isolation per-game in Steam
export STEAM_MULTIPLE_XWAYLANDS=1

# Don't wait for buffers to idle on the client side before sending them to gamescope
export vk_xwayland_wait_ready=false

export XCURSOR_THEME=steam

# Workaround for Steam login issue while Steam client change propagates out of Beta
touch ~/.steam/root/config/SteamAppData.vdf || true

export STEAM_UPDATEUI_PNG_BACKGROUND=/usr/share/steamos/steamos.png

ulimit -n 524288

# Create run directory file for startup and stats sockets
#   shellcheck disable=SC2030 # (broken warning)
tmpdir="$([[ -n ${XDG_RUNTIME_DIR+x} ]] && mktemp -p "$XDG_RUNTIME_DIR" -d -t gamescope.XXXXXXX)"
socket="${tmpdir:+$tmpdir/startup.socket}"
stats="${tmpdir:+$tmpdir/stats.pipe}"
# Fail early if we don't have a proper runtime directory setup
#   shellcheck disable=SC2031 # (broken warning)
if [[ -z $tmpdir || -z ${XDG_RUNTIME_DIR+x} ]]; then
	echo >&2 "!! Failed to find run directory in which to create stats session sockets (is \$XDG_RUNTIME_DIR set?)"
	exit 0
fi

export GAMESCOPE_STATS="$stats"
mkfifo -- "$stats"
mkfifo -- "$socket"

# Attempt to claim global session if we're the first one running (e.g. /run/1000/gamescope)
linkname="gamescope-stats"
#   shellcheck disable=SC2031 # (broken warning)
sessionlink="${XDG_RUNTIME_DIR:+$XDG_RUNTIME_DIR/}${linkname}" # Account for XDG_RUNTIME_DIR="" (notfragileatall)
lockfile="$sessionlink".lck
exec 9>"$lockfile" # Keep as an fd such that the lock lasts as long as the session if it is taken
if flock -n 9 && rm -f "$sessionlink" && ln -sf "$tmpdir" "$sessionlink"; then
	# Took the lock.  Don't blow up if those commands fail, though.
	echo >&2 "Claimed global gamescope stats session at \"$sessionlink\""
else
	echo >&2 "!! Failed to claim global gamescope stats session"
fi

gamescope --xwayland-count 2 -w 1280 -h 800 --default-touch-mode 4 --hide-cursor-delay 3000 --max-scale 2 --fade-out-duration 200 -e -R "$socket" -T "$stats" -O DP-1,eDP-1 --cursor-hotspot 5,3 --cursor /usr/share/steamos/steamos-cursor.png &
gamescope_pid="$!"

if read -r -t 3 response_x_display response_wl_display <> "$socket"; then
	export DISPLAY="$response_x_display"
	export GAMESCOPE_WAYLAND_DISPLAY="$response_wl_display"
	# We're done!
else
	kill -9 "$gamescope_pid"
	wait
	exit 0
	# SDDM will restart us
fi

xbindkeys -f /etc/xbindkeysrc

steamargs=("-steamos3" "-steampal" "-steamdeck" "-gamepadui")

# steamargs+=("-steamfs")

(while true; do
    /usr/lib/hwsupport/power-button-handler.py
done) &

if [[ -x $HOME/devkit-game/devkit-steam ]]; then
	mangoapp &
	"$HOME"/devkit-game/devkit-steam "${steamargs[@]}"
else
	mangoapp &
	steam "${steamargs[@]}"
fi

# Ask gamescope to exit nicely
kill $gamescope_pid

# Start a background sleep for five seconds because we don't trust it
sleep 5 &
sleep_pid=$!

# Wait for gamescope or the sleep to finish for timeout purposes
ret=0
wait -n $gamescope_pid $sleep_pid || ret=$?

# If we get a SIGTERM/etc while waiting this happens.  Proceed to kill -9 everything but complain
if [[ $ret = 127 ]]; then
	echo >&2 "gamescope-session: Interrupted while waiting on teardown, force-killing remaining tasks"
fi

# Kill all remaining jobs and warn if unexpected things are in there (should be just sleep_pid, unless gamescope failed
# to exit in time or we hit the interrupt case above)
for job in $(jobs -p); do
	# Warn about unexpected things
	if [[ $ret != 127 && $job = "$gamescope_pid" ]]; then
		echo >&2 "gamescope-session: gamescope timed out while exiting, killing"
	elif [[ $ret != 127 && $job != "$sleep_pid" ]]; then
		echo >&2 "gamescope-session: unexpected background pid $job at teardown: "
		# spew some debug about it
		ps -p "$job" >&2
	fi
	kill -9 "$job"
done

# This should just be waiting on kill -9'd things. Another signal will cause us to give up, but we should be a little
# stubborn about not letting the session die with gamescope holding on to things.
wait
