#!/bin/bash
#
# chkconfig: - 91 35
# description: Starts and stops vncserver. \
#              used to provide remote X administration services.

### BEGIN INIT INFO
# Provides: vncserver
# Required-Start: $network $named
# Required-Stop: $network $named
# Default-Start:
# Default-Stop: 0 1 2 3 4 5 6
# Short-Description: start|stop|restart|try-restart|status|force-reload vncserver
# Description: control vncserver which exports your desktop
### END INIT INFO

# Source function library.
. /etc/init.d/functions

[ -r /etc/sysconfig/vncservers ] && . /etc/sysconfig/vncservers

prog=$"VNC server"
VNC_USER="###USERNAME###"
VNC_DISPLAY="###VNC_DISPLAY###"
VNCSERVER_ARGS="-depth 24 -geometry 1280x800"

RETVAL=0

start() {
    [ "$EUID" != "0" ] && exit 4
    
    # Source networking configuration.
    . /etc/sysconfig/network

    # Check that networking is up.
    [ ${NETWORKING} = "no" ] && exit 1

    [ -x /usr/bin/vncserver ] || exit 5
    [ -x /usr/bin/Xvnc ] || exit 5

    echo -n $"Starting $prog for ${VNC_USER}: "
    RETVAL=0
    if [ ! -d /tmp/.X11-unix ]
    then
        mkdir -m 1777 /tmp/.X11-unix || :
        restorecon /tmp/.X11-unix 2>/dev/null || :
    fi

    runuser -l ${VNC_USER} -c "vncserver :${VNC_DISPLAY} ${VNCSERVER_ARGS}" < /dev/null
    RETVAL=$?

# As written in https://bugzilla.redhat.com/show_bug.cgi?id=523974 (LSB
# compliance) start of already running service is OK.
    [ "$RETVAL" -eq 98 ] && RETVAL=0

    return "$RETVAL"
}

stop() {
    [ "$EUID" != "0" ] && exit 4

    echo -n $"Shutting down $prog for ${VNC_USER}: "

    runuser ${USER} -c "vncserver -kill :${VNC_DISPLAY}" >/dev/null 2>&1
    RETVAL=$?

    return "$RETVAL"
}

# See how we were called.
case "$1" in
  start)
        start
        ;;
  stop)
        stop
        ;;
  restart|force-reload)
        stop
        sleep 3
        start
        ;;
  condrestart)
#       https://bugzilla.redhat.com/show_bug.cgi?id=508367
#       echo "condrestart is obsolete, use try-restart instead"
        if [ -e /var/lock/subsys/Xvnc ]; then
            stop
            sleep 3
            start
        fi
        ;;
  try-restart)
        if [ -e /var/lock/subsys/Xvnc ]; then
            stop
            sleep 3
            start
        fi
        ;;
#  status)
#        status Xvnc
#        RETVAL=$?
#        ;;
#  reload)
#        exit 3
#        ;;
  *)
#        echo $"Usage: $0 {start|stop|restart|try-restart|status|force-reload}"
        echo $"Usage: $0 {start|stop|restart|try-restart|force-reload}"
        exit 2
esac

exit "$RETVAL"

