#!/bin/sh
#
# qserv-wmgr  This shell script takes care of starting and stopping
#             Qserv worker management service.

### BEGIN INIT INFO
# Provides: qserv-wmgr
# Short-Description: start and stop qserv worker management service
# Description: qserv-wmgr is the Qserv worker management service \
#              It provides RESTful HTTP interface which is a single \
#              end-point for all worker communication and control.
### END INIT INFO

DIR=$(cd "$(dirname "$0")"; pwd -P)

# Source functions library.
. ${DIR}/qserv-functions

NAME="qserv-wmgr"
DAEMON=${NAME}

source_sysconfig ${DIR}

# Check variables which are not controlled by application
check_writable ${NAME} "QSERV_RUN_DIR"
check_writable ${NAME} "QSERV_PID_DIR"
check_writable ${NAME} "QSERV_LOG_DIR"

start=qservWmgr.py
config=${QSERV_RUN_DIR}/etc/${NAME}.cnf
pidfile=${QSERV_PID_DIR}/${NAME}.pid
lockfile=${QSERV_RUN_DIR}/var/lock/subsys/${NAME}
logfile=${QSERV_LOG_DIR}/${NAME}.log
starttimeout=1

# Disabling buffering in python in order to enable "real-time" logging.
export PYTHONUNBUFFERED=1

cmd="${PYTHON} ${start} -c ${config} -v >> ${logfile} 2>&1 &"

start_cmd() {
    start -p $pidfile -l $lockfile -t ${starttimeout} $NAME "${cmd}"
    ret=$?
    [ $ret -eq 0 ] || echo "See startup logfile : ${logfile}"
    return $ret
}

stop_cmd() {
    stop -p $pidfile -l $lockfile $NAME
}

# See how we were called.
case "$1" in
    start)
        start_cmd
        ;;
    stop)
        stop_cmd
        ;;
    restart)
        stop_cmd
        start_cmd
        ;;
    condrestart|try-restart)
        if status_of_proc -p ${pidfile} "$DAEMON" "$NAME" >&/dev/null; then
            stop_cmd
            start_cmd
        fi
        ;;
    status)
        status_of_proc -p ${pidfile} "$DAEMON" "$NAME" && exit 0 || exit $?
        ;;
    *)
        echo "Usage: $0 {start|stop|restart|reload|status|condrestart|try-restart}"
        exit 2
        ;;
esac

exit $?
