#!/bin/bash
#
CMD=$(basename $0)
CMDVER="1.0"
CMDSTR="$CMD v$CMDVER (2017/11)"

set -e -u

default_cfgfile_content="# .vnc/default.config - config for 'ku-vncserver-start' util
#
geometry='1080x1024'

# use '-localhost=no' for tigervncserver
parms=
"

check_config_dir()
{
	[ -d "$cfgdir" ] || {
		mkdir "$cfgdir"
		echo "  warning: config dir '$cfgdir' created" >&2
	}
	[ -f "$cfgfile" ] || {
		echo "$default_cfgfile_content" >"$cfgfile"
		echo "  warning: config file '$cfgfile' created" >&2
		echo "  edit it and relaunch the server" >&2
		return 1
	}
	[ -f "$cfgdir/passwd" ] || {
		echo "  error: vncserver password not set, run 'vncpasswd'" >&2
		echo "  command to set one, and then relaunch the server" >&2
		return 1
	}
}

# (MAIN)

myname=$(uname -n)
cfgdir="$HOME/.vnc"
cfgfile="$cfgdir/default.config"

desktop_id_file="$cfgdir/current-desktop-id"
desktop_id=

check_config_dir || exit $?

[ -f "$cfgfile" ] && . $cfgfile

[ -f "$desktop_id_file" ] && {
	desktop_id=$(cat "$desktop_id_file")
	ps=$(ps uww | grep "vnc.* :$desktop_id " | fgrep -v grep) || :

	[ "X$ps" = "X" ] && {
		echo "  warning: removing stale desktop-id file (desktop_id=$desktop_id)" >&2
		rm -f "$desktop_id_file"
		desktop_id=
	}
}


# sanity checks
#
[ "X$geometry" != "X" ] && geometry="-geometry $geometry"


if [ "$desktop_id" = "" ]
then
	out=$(vncserver $geometry $parms 2>&1)
	echo "$out"

	# sample output when all ok:
	#
	# New 'myhost.my.domain:1 (username)' desktop is myhost.my.domain:1
	#
	# Starting applications specified in /home/username/.vnc/xstartup
	# Log file is /home/username/.vnc/myhost.my.domain:1.log
	#
	#
	# 2021-11-03
	# - more generic parsing to cope with tigervnc version
	# - checks for a valid desktop_id 
	#
	#desktop_id=$(echo "$out" | grep 'desktop is ' | sed -e "s/.*desktop is $myname://")

	# tigervnc version:
	# New 'private.core.klabs:1 (kanna)' desktop at :1 on machine private.core.klabs

	desktop_id=$(echo "$out" | grep 'New .* desktop ' | sed -e 's/.*://' -e 's/\s.*//')

	# 2023-11-11
	# tigervnc >1.12 (devuan daedalus)
	# New Xtigervnc server 'vua5desktop.core.klabs:1 (kanna)' on port 5901 for display :1.
	#
	[ "X$desktop_id" = "X" ] && {
		desktop_id=$(echo "$out" | grep 'New Xtigervnc server ' | sed -e 's/.*display ://' -e 's/\.$//')
	}

	[ "X$desktop_id" = "X" ] && {
		echo -e "\n  ERROR: something goes wrong, cannot determine desktop ID\n" >&2
		exit 1
	}
	echo
	echo "  CURRENT DESKTOP ID: $desktop_id"
	echo
	echo "$desktop_id" >"$desktop_id_file"
else
	echo -e "\n  ERROR: server alredy active on desktop: $desktop_id\n" >&2
	exit 1
fi

exit 0
