#!/bin/sh

export XAUTHORITY="/var/lib/vgl/vgl_xauth_key"

gracefull_stop()
{
    kill $xpid
}

# setting up a trap
trap "gracefull_stop" TERM INT

# select next free display if not specified
if [ -z "$display" ]; then
	last_display=`find /tmp/ -maxdepth 1 -type f -name '.X*-lock' |
		sed -ne 's,^/tmp/\.X\([[:digit:]]\+\)-lock$,\1,p' |
		sort -n |
		tail -1`
	[ -z "$last_display" ] || display=":$((1+last_display))"
fi

# set up default Xauth info for this machine
removelist=
authdisplay=${display:-:0}
mcookie=`mcookie`
for displayname in "$authdisplay" "`hostname -f`$authdisplay"; do
	if ! xauth list "$displayname" |fgrep -qs "$displayname "; then
		xauth add "$displayname" . "$mcookie"
		removelist="$displayname $removelist"
	fi
done
[ "`stat -c%a $XAUTHORITY`" = "640" ] || chmod 640 $XAUTHORITY

X -nolisten tcp -auth $XAUTHORITY&
xpid=$!
wait $xpid
