#!/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() {
	feh --bg-fill "/usr/share/wallpapers/Treuchtlingen/$1.png"
}

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

	display_status "$status"
	
	sleep 1

	while ! /usr/lib/nagios/plugins/check_host -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 '{ match($0, /tras-([0-9]+)/, i) ; print i[1] }')"
	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"
	wait_for "172.17.$trasnr.1" "$trastype-warte-auf-$networktype"
	wait_for "172.16.16.$trasnr" "$trastype-warte-auf-vpn-endpunkt"
	wait_for 172.16.16.1 "$trastype-warte-auf-vpn-server"
	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

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
