#!/bin/sh

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_session_resume_time_unix_local_tz() {
	date --date "$(x2golistsessions | awk -v"x2go_session=$X2GO_SESSION" -F'|' '$2==x2go_session{ print $11 }')" +%s
}

# returns the autosuspend time in seconds
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))"
}

log() {
    FORMAT="$1"
    shift 1
    printf "%s $FORMAT\n" "$(date --rfc-3339=ns)" "$@" >> "${XDG_CACHE_HOME:-$HOME/.cache}/.x2go-autosuspend-log"
}

if [ "$1" = "--handle-suspend" ] ; then
	log "Handling suspend"
	if [ "$(get_session_status)" = "R" ] ; then
		sleep 3
		AUTOSUSPEND_TIME="$(get_autosuspend_time)"
		SESSION_RESUME_TIME="$(get_session_resume_time_unix_local_tz)"
		if [ "$((SESSION_RESUME_TIME + AUTOSUSPEND_TIME))" -gt "$(date +%s)" ] ; then
			log "Suspend happend too soon after session restart, ignoring."
			exit
		fi
		x2gosuspend-session &
		log "Waiting for the suspend to take effect"
		while [ "$(get_session_status)" = "R" ] ; do
			sleep 1
		done
	else
		log "Already suspended, skipping suspend step and just wait for session resume"
	fi
	log "Waiting for session resume"
	while [ "$(get_session_status)" = "S" ] ; do
		sleep 10 # Sleep to account for the `xset s q` trick not always working
		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
	done
	log "No longer suspended, session status is %s" "$(get_session_status)"
	AUTOSUSPEND_TIME="$(get_autosuspend_time)"
	log "Restoring the suspend time setting to %s seconds" "$AUTOSUSPEND_TIME"
	xset s "$AUTOSUSPEND_TIME" 0
	exit
fi


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

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