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