#!/usr/bin/env zsh

# bail out if xscreensaver isn't installed
if [[ ! -x =xscreensaver ]]; then
	echo "no xscreensaver command found, ${0:t} bailing out" >&2
	exit 0
fi

# record our own PID to avoid duplicate invocations
PIDFILE="/dev/shm/${0:t}.pid"

# check for already running script
if [[ -f ${PIDFILE} ]]; then
	for i in $(pidof -x ${0:t}); do
		if [[ ${i} -eq $(cat ${PIDFILE}) ]]; then
			echo "${0:t} already running!" >&2
			exit 1
		fi
	done
fi

# record current PID
echo ${$} > ${PIDFILE}

# wait a bit for everything to start
sleep 30

# check whether xscreensaver itself is running and start it if not
if ! systemctl --user --quiet is-active xscreensaver.service; then
	systemctl --user start xscreensaver.service
fi

# retrieve current Xorg screen size so we know where the corners are
xrandr | grep ^Screen | grep -Eo 'current [[:digit:]]+ x [[:digit:]]+' | cut -d' ' -f2,4 | read max_x max_y
echo "read screen size as ${max_x} x ${max_y}"

# main loop
while true; do

	# retrieve current mouse position and set environment variables
	eval $(xdotool getmouselocation --shell)

	# a Steam game is running
	if ps axfu | grep -v grep | grep -q '/home/nipsy/.local/share/Steam/steamapps/common/'; then

		# make sure xscreensaver is even running before telling it to stay idle
		if pidof xscreensaver &>/dev/null; then
			sleep 5
			xscreensaver-command -deactivate &>/dev/null
		fi

	# keep xscreensaver deactivated if we're in the bottom right corner of the screen
	elif [[ ${X} -eq $((max_x - 1)) && ${Y} -eq $((max_y - 1)) ]]; then

		# make sure xscreensaver is even running before telling it to stay idle
		if pidof xscreensaver &>/dev/null; then
			sleep 5
			xscreensaver-command -deactivate &>/dev/null
		fi

	# mouse is in the top left corner -- potentially activate xscreensaver right now
	elif [[ ${X} -eq $((max_x - max_x)) && ${Y} -eq $((max_y - max_y)) ]]; then

		# sleep a bit and then check mouse coordinates again
		sleep 5
		eval $(xdotool getmouselocation --shell)

		# mouse is still in the top left corner -- we must really want to activate xscreensaver
		if [[ ${X} -eq $((max_x - max_x)) && ${Y} -eq $((max_y - max_y)) ]]; then

			# make sure xscreensaver is actually running
			if pidof xscreensaver &>/dev/null; then

				# make sure it hasn't already activated
				if ! xscreensaver-command -time | grep -q 'screen blanked since'; then

					# activate it!
					xscreensaver-command -activate &>/dev/null

				fi

			fi

		fi

	fi

	# die off if we're no longer running on a connected Xorg screen any longer -- this should be the normal termination path for this script
	if ! xdpyinfo &>/dev/null; then
		rm ${PIDFILE}
		exit 0
	fi

	# arbitrary sleep for script to avoid CPU sucking infinite loop
	sleep 5

done

# exit with error since we should never get here
exit 1
