#!/usr/bin/env bash
### BEGIN INIT INFO
# Provides:          cmon-cloud
# 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-cloud daemon
# Description:       starts cmon-cloud using start-stop-daemon
### END INIT INFO

DESC="the cmon-cloud daemon"
NAME=cmon-cloud
DAEMON=/usr/sbin/${NAME}
HOST=127.0.0.1
PORT=9518

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

DAEMONOPTS="-log_file /var/log/cmon-cloud.log"
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"

# on systemd this might be not set properly
PATH=/usr/bin:/usr/sbin:/bin:${PATH}

# lets try to read env-variables from /etc/profile
if [ -f /etc/profile ]; then
    source /etc/profile
fi

pidof_prog() {
    if [ -f $PIDFILE ]; then
        pidof $NAME | tr ' ' '\n' | grep $(cat $PIDFILE) 2>/dev/null
    fi
}

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() {
    PID=$(pidof_prog)
    if [ -n "$PID" ]; then
        printf "$NAME is already running with pid $PID\n"
        return 1
    else
        $DAEMON_START
    fi
}

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
