#!/usr/bin/env bash
### BEGIN INIT INFO
# Provides:          cmon-ssh
# Required-Start:    $local_fs $network $named $time $syslog
# Required-Stop:     $local_fs $network $named $time $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: starts cmon-ssh daemon
# Description:       starts cmon-ssh using start-stop-daemon
### END INIT INFO

DESC="the cmon-ssh daemon"
NAME=cmon-ssh
DAEMON=/usr/share/cmon-ssh/cmon-ssh
HOST=127.0.0.1
PORT=9511

DAEMONUSER=root
PIDFILE=/var/run/$NAME.pid

CONFIGDIR_CMON=/etc/cmon.d/
DAEMONOPTS="-cmon_d $CONFIGDIR_CMON -host $HOST -port $PORT"
STOP_SCHEDULE="${STOP_SCHEDULE:-QUIT/5/TERM/5/KILL/5}"

DAEMON_START="start-stop-daemon --quiet --make-pidfile --pidfile $PIDFILE --background --chuid $DAEMONUSER --oknodo --exec $DAEMON --start -- $DAEMONOPTS"
DAEMON_STOP="start-stop-daemon --stop --quiet --pidfile $PIDFILE --retry=$STOP_SCHEDULE --name $NAME --oknodo"
DAEMON_RELOAD="start-stop-daemon --stop --quiet --signal USR1 --pidfile $PIDFILE --name $NAME"
DAEMON_STATUS="d_status"
PIDOF=/sbin/pidof
[ -f $PIDOF ] || PIDOF=/bin/pidof

test -x $DAEMON || exit 0
test -x $PIDOF || exit 0

if [ -f /etc/init.d/functions ]; then
    source /etc/init.d/functions
    DAEMON_START="daemon --check $NAME --user $DAEMONUSER $DAEMON $DAEMONOPTS &"
    DAEMON_STOP="killproc $DAEMON"
    DAEMON_RELOAD="${DAEMON_STOP}; ${DAEMON_START}"
    DAEMON_STATUS="status $DAEMON"
fi

start() {
    WEBROOT="/var/www/html/clustercontrol"
    [ -d $WEBROOT ] || WEBROOT="/var/www/clustercontrol"
    grep -q ^"define('SSH_ENABLED', true)" $WEBROOT/bootstrap.php || exit 0

    $PIDOF cmon-ssh &>/dev/null || $DAEMON_START
}

stop() {
    $DAEMON_STOP
    rm -f $PIDFILE &>/dev/null
}

reload() {
    $DAEMON_RELOAD
}

_status() {
    $DAEMON_STATUS
}

d_status() {
    if [ -f $PIDFILE ]; then
        if kill -0 $(cat "$PIDFILE"); then
            echo "$NAME is running (pid $(cat $PIDFILE))."
        else
            echo "$NAME process is dead, but pidfile exists."
        fi
    else
        echo "$NAME is not running."
    fi
}

case "$1" in
    start)
        echo "Starting $NAME"
        start
    ;;
    stop)
        echo "Stopping $NAME"
        stop
    ;;
    restart)
        echo "Restarting $NAME"
        stop
        start
    ;;
    reload)
        echo "Reloading $NAME configuration"
        reload
    ;;
    status)
        _status
    ;;
    *)
        echo "Usage: $0 {start|stop|restart|reload|status}"
        exit 2
    ;;
esac

exit 0
