#!/bin/bash

# Turn numlock on if numlockx is present
whereis numlockx >/dev/null 2>/dev/null && numlockx on

# Read servers from x2goclient config
X2GO_SERVERS="$( awk -F '=' '/^host=/{ hosts = hosts $2 " " } END { print hosts }' < ~/.x2goclient/sessions )"

X2GO_SIZE_OPTION="--thinclient"

display_status() {
	if [ -n "$DISPLAY" ] ; then
		feh --bg-fill "/usr/share/wallpapers/Treuchtlingen/$1.png"
	else
		printf "Status: %s\n" "$1"
	fi
}

wait_for() {
	local ip="$1"
	local status="$2"
	[ -z "$ip" ] && return 1
	[ -z "$status" ] && return 1

	display_status "$status"
	printf "Waiting for: %s\n" "$ip"

	sleep 1

	while ! /usr/lib/nagios/plugins/check_icmp -m 1 -H $ip
	do
		      sleep 1
	done
}

display_wallpaper_delayed() {
	sleep 3
	display_status Fuchs_auf_dukelgrau
}

if [[ "$HOSTNAME" =~ ^tras- ]] ; then
	trasnr="$(printf "%s\n" "$HOSTNAME" | awk -F - '{ print $2 }')"
	trastype="homeoffice"
	networktype="wlan"
	if ip l | grep ' enp[a-z0-9]*:' | grep -q UP ; then
		trastype="remote-client"
		networktype="netzwerk"
	fi
	wait_for 127.0.0.1 "$trastype-starte"
	display_status "$trastype-warte-auf-$networktype"
	while ! ip r | grep -q '^default via' && ! /usr/lib/nagios/plugins/check_icmp -m 1 -H $X2GO_SERVERS ; do
		sleep .2
	done
	default_gateway="$( ip r | awk '/^default via/ { print $3 }')"
	wait_for "$default_gateway $X2GO_SERVERS" "$trastype-warte-auf-$networktype"
	if /usr/lib/nagios/plugins/check_icmp -m 1 -H $X2GO_SERVERS ; then
		echo "fastpath! Bypassing network check."
		sleep .1
	elif printf "%s" "$default_gateway" | grep -q "\.49$" ; then
		wait_for "172.16.1.1" "$trastype-warte-auf-vpn-server"
	else
		wait_for "172.16.16.$trasnr" "$trastype-warte-auf-vpn-endpunkt"
		wait_for "172.16.16.1" "$trastype-warte-auf-vpn-server"
	fi
	wait_for "$X2GO_SERVERS" "$trastype-warte-auf-x2go"
	display_status $trastype-success
elif [[ "$HOSTNAME" =~ ^tc- ]] ; then
	#wait_for 127.0.0.1 thinclient-starte
	#wait_for "$X2GO_SERVERS" thinclient-warte-auf-x2go
	#display_status thinclient-success
	true # noop
else
	true # noop
fi

if [ -z "$DISPLAY" ] ; then
	echo "No DISPLAY set, not starting gui"
	exit 2
fi

display_wallpaper_delayed &

# Start X2goclient
cp -r "$HOME/.config/x2go" "$HOME/.x2goclient"

/usr/bin/x2goclient \
	--no-menu \
	--maximize \
	"$X2GO_SIZE_OPTION" \
	--xinerama \
	--link=adsl \
	--kbd-layout=de \
	--kbd-type=pc105/de \
	--set-kbd=1 \
	--geometry=fullscreen \
	--haltbt \
	--no-session-edit \
	--add-to-known-hosts \
	--background=/usr/share/wallpapers/Treuchtlingen/Einfarbig-Waldgrün.svg \
	--branding=/usr/share/icons/Treuchtlingen/scaleable/categories/fuchs.svg
