#!/bin/sh
# vzcloudm virtuozzo worker startup script
#
# Copyright (C) 2009-2010 PlusServer AG. All rights reserved.
#
# chkconfig: 2345 98 10
# description: Controls vzcloudm virtuozzo worker
#
# Source function library.
. /etc/rc.d/init.d/functions

# Add /usr/local/bin to $PATH to give our custom installed old rsync version
# preference over the system rsync command
PATH="/usr/local/sbin:/usr/local/bin:/sbin:/usr/sbin:/bin:/usr/bin"
export PATH

# This line is needed to cheat /etc/rc.d/rc which expects the action word
E_USAGE=1
E_START=2
E_STOP=3
E_STOP_TIMEOUT=4
S_RUNNING=0
S_STOPPED=1

NAME=vzcloudm-vw
ROOT=/opt/vzcloudm
BIN=${ROOT}/bin
RUN=${ROOT}/run
EXECUTABLE=vw.py
DAEMON=${BIN}/${EXECUTABLE}
PIDFILE=${RUN}/vw.pid
SHUTDOWN_WAIT_PERIOD=900
RETVAL=0

test -x ${DAEMON} || exit 0

function is_running() {
    ${DAEMON} --check-running
    return $?
}

case "$1" in
start)
    if ! is_running; then
        ${DAEMON}
        RETVAL="${?}"
    fi

    if [ "${RETVAL}" == "0" ]; then
        action $"Starting ${NAME}: " /bin/true
    else
        action $"Starting ${NAME}: " /bin/false
    fi
    ;;
stop)
    if is_running; then
        pid=$(cat ${PIDFILE})
        kill "${pid}"
        RETVAL="${?}"
        i=0
        while is_running; do
            if [ $i -ge ${SHUTDOWN_WAIT_PERIOD} ]; then
                RETVAL="${E_STOP_TIMEOUT}"
                break
            fi
            sleep 0.5
            i=$(($i + 1))
        done
    fi

    if [ "${RETVAL}" == "0" ]; then
        action $"Stopping ${NAME}: " /bin/true
    else
        action $"Stopping ${NAME}: " /bin/false
    fi
    ;;
restart)
    echo "Restarting ${NAME}"
    $0 stop && \
    $0 start
    ;;
condrestart)
    if is_running; then
        echo "Restarting ${NAME}"
        $0 stop && \
        $0 start
    fi
    ;;
status)
    if is_running; then
        echo "Status of ${NAME} is running"
        RETVAL="${S_RUNNING}"
    else
        echo "Status of ${NAME} is not running"
        RETVAL="${S_STOPPED}"
    fi
    ;;
*)  echo "Usage: ${0} {start|stop|restart|status}"
    RETVAL="${E_USAGE}"
    ;;
esac

exit ${RETVAL}
