#!/bin/bash

if [ -z "$X2GO_SESSION" ] ; then
	echo "Not an x2go session -> Not starting autosuspend."
	exit
fi

get_session_status() {
	x2golistsessions | awk -v"x2go_session=$X2GO_SESSION" -F'|' '$2==x2go_session{ print $5 }'
}

get_autosuspend_time() {
	AUTOSUSPEND_TIME=""

	# if configuration file exists, read it
	if [ -e "$HOME/.config/x2go-autosuspend-time" ] ; then
		AUTOSUSPEND_TIME="$(head -n 1 "$HOME/.config/x2go-autosuspend-time" | grep '^[0-9]*$' )"
	fi

	[ -n "$AUTOSUSPEND_TIME" ] || AUTOSUSPEND_TIME="19"

	printf "%s\n" "$((AUTOSUSPEND_TIME*60))"
}

if [ "$1" = "--handle-suspend" ] ; then
	sleep 3
	x2gosuspend-session &
	# Wait for the suspend to take effect
	while [ "$(get_session_status)" = "R" ] ; do
		sleep 1 
	done
	if [ "$(get_session_status)" = "S" ] ; then
		xset s q # Wait for the x-server to come back and answer again
		# The wait part works, because the query will block until the session gets resumed again
	fi
	# Restore the suspend time setting
	xset s "$(get_autosuspend_time)" 0
fi


#xautolock -time "$AUTOSUSPEND_TIME" -locker x2gosuspend-session

xset s "$(get_autosuspend_time)" 0
xss-lock -- "$0" --handle-suspend
