8aca67
#!/bin/sh
8aca67
8aca67
USER="$1"
8aca67
INSTANCE="$2"
8aca67
8aca67
die() {
8aca67
	echo "FATAL: ${@:-}" >&2
8aca67
	exit 2
8aca67
}
8aca67
8aca67
cleanup() {
8aca67
	[ -n "$VNCPID" ] || return
8aca67
	if kill -0 $VNCPID 2>/dev/null; then
8aca67
		kill $VNCPID
8aca67
	fi
8aca67
}
8aca67
8aca67
trap cleanup TERM INT HUP
8aca67
8aca67
[ -n "$USER" -a -n "$INSTANCE" ] || die "Invalid usage!"
8aca67
8aca67
/usr/sbin/runuser -l "$USER" -c "/usr/bin/vncserver ${INSTANCE}"
8aca67
[ $? -eq 0 ] || die "'runuser -l $USER' failed!"
8aca67
8aca67
# Wait up to 5 seconds for vncserver to be up
8aca67
for tries in $(seq 1 50); do
8aca67
	[ -e "~$USER/.vnc/$(hostname)${INSTANCE}.pid" ] && break
8aca67
	sleep 0.1
8aca67
done
8aca67
8aca67
eval HOME=~$USER
8aca67
8aca67
VNCPID=$(cat "$HOME/.vnc/$(hostname)${INSTANCE}.pid" 2>/dev/null || true)
8aca67
[ -n "$VNCPID" ] || die "'vncserver ${INSTANCE}' failed to start after 5 seconds!"
8aca67
8aca67
echo "'vncserver ${INSTANCE}' has PID $VNCPID, waiting until it exits ..."
8aca67
8aca67
while kill -0 $VNCPID 2>/dev/null; do
8aca67
	sleep 5
8aca67
done
8aca67
8aca67
echo "PID $VNCPID exited, exiting ..."