# Author: Theodore Zacharia
# V0.1  : Initial Release
# V0.2  : 24/03/2025 - add -x option
#
# This script provides support for running a VNC service on an
# unstable host, so it checks if the service is running and restarts it
#

# *** Globals
TRACE=0
DOLOOP=0
CHECKTIME=10
DOX11DIRECT=0


# *** Functions
_usage()
{
	echo "usage: $0 [-h] [-t] [-x] [-l|-L]"
	echo "where"
	cat <<- _EOF_
	  -h        Displays this help message
	  -t        Set trace on
	  -x        Set to call x11 direct rather than as a service
	  -L or -l  Loops, checking the service every $CHECKTIME seconds
_EOF_
}


# *** Mainline

# process input parameters
while getopts thlLx AOPT
do
case $AOPT in
	t) TRACE=1 ;; # set TRACE mode
	l|L) DOLOOP=1 ;;
	x) DOX11DIRECT=1 ;;
	h) _usage
	   exit 1 ;;
	*) echo "$AOPT is an invalid option" >&2
	   exit 2 ;;
esac
done

shift $((OPTIND-1))

if [ $DOLOOP -eq 1 ]
then
	if [ `whoami` = "root" ]
	then
		echo "running as root";
	else
		echo "Ideally do as root"
	fi
fi

# loop runs at least once
while :
do
	if [ $TRACE -gt 0 ] ; then echo "checking vnc at `date`" ; fi
	CT=`ps -ef | grep x11vnc | grep -v -c grep`
	if [ $CT -lt 1 ]
	then
		echo "starting x11vnc at `date` as user `whoami`"
		if [ $DOX11DIRECT -eq 1 ]
		then
			x11vnc -display :0 -auth /var/run/lightdm/root/:0 -forever -loop -noxdamage -repeat -rfbauth ~/.vnc/passwd -rfbport 5900
		else
			if [ `whoami` = "root" ]
			then
				systemctl start x11vnc.service
			else
				sudo systemctl start x11vnc.service
			fi
		fi
	else
		sleep $CHECKTIME
	fi
	if [ $DOLOOP -eq 0 ] ; then break ; fi
done