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