#!/bin/sh

### BEGIN INIT INFO
# Provides:          shinken
# Required-Start:    $local_fs
# Required-Stop:     $local_fs
# Default-Start:     2 3 4 5
# Default-Stop:      S 0 1 6
# Short-Description: Shinken monitoring daemon
# Description:       Shinken is a monitoring tool composed of many separated modules:
#     - arbiter     : the main one : control everything else.
#     - scheduler   : receives checks/actions from arbiter. Schedules & forwards them to pollers.
#     - poller      : receives the checks from a scheduler. Launch them and returns results
#     - broker      : manage results by looking at scheduler. Like export to flat file or db.
#     - reactionner : manage the failed checks by looking at scheduler. 
### END INIT INFO


# http://refspecs.freestandards.org/LSB_3.1.1/LSB-Core-generic/LSB-Core-generic/iniscrptact.html


NAME="shinken"

AVAIL_MODULES="scheduler poller reactionner broker arbiter"

## SHINKEN_MODULE_FILE is set by shinken-* if it's one of these that's calling us.
if [ -z "$SHINKEN_MODULE_FILE" ]; then
    SCRIPTNAME=$0
    _usage_mods_="[ <$AVAIL_MODULES> ]"
else
    SCRIPTNAME=$SHINKEN_MODULE_FILE
fi

curpath=$(dirname "$0")

## Default paths :
BIN="/usr/local/shinken/bin"
VAR="/usr/local/shinken/var"
ETC="/usr/local/shinken/etc"

## This permit to overhidde the default "default shinken cfg file" : 
[ -z "$SHINKEN_DEFAULT_FILE" ] && SHINKEN_DEFAULT_FILE="/etc/default/$NAME" 
## so you can now do:
## bash -c "SHINKEN_DEFAULT_FILE=$your_own_default_file $init_path/shinken $action $args"
## to easily use your own config

#echo "Using $SHINKEN_DEFAULT_FILE .."

usage() {
    cat << END
Usage: $SCRIPTNAME [ -d ] {start|stop|restart|status|check} $_usage_mods_

 -d  start requested module(s) in debug mode, only useful with start|restart

END
}

if [ "$1" = "-d" ]; then
    DEBUG="1"
    shift
fi

if [ $# -eq 0 ]; then
    usage >&2
    exit 2
fi

CMD=$1
shift
SUBMODULES=$*

if [ -z "$SUBMODULES" ]; then
    SUBMODULES=$AVAIL_MODULES
else
    # verify given modules
    for mod1 in $SUBMODULES; do
        found=0
        for mod2 in $AVAIL_MODULES; do
            [ $mod1 = $mod2 ] && found=1;
        done
        [ $found = 0 ] && { usage >&2 ; exit 2 ; }
    done
fi


# Read configuration variable file if it is present
[ -r "$SHINKEN_DEFAULT_FILE" ] && . "$SHINKEN_DEFAULT_FILE"

# Load the VERBOSE setting and other rcS variables
[ -f /etc/default/rcS ] && . /etc/default/rcS

# Define LSB log_* functions.
. /lib/lsb/init-functions


################################################

#
# return the pid for a submodule
#
getmodpid() {
    mod=$1
    pidfile="$VAR/${mod}d.pid"
    if [ -s $pidfile ]; then
        cat $pidfile
    fi
}


#
# Display status
#
do_status() {
    mod=$1
    pidfile="$VAR/${mod}d.pid"
    [ -e "$pidfile" ] || {
        echo "$mod NOT RUNNING (pidfile ($pidfile) not exist)"
        return 3
    }
    [ -r "$pidfile" ] || {
        echo "$mod NOT RUNNING (pidfile ($pidfile) unreadable)"
        return 3
    }
    pid=$(cat "$pidfile")
    if [ -z "$pid" ]; then
        echo "$mod NOT RUNNING (pid file empty)"
        return 4
    fi
    ps -p "$pid" >/dev/null 2>&1
    rc=$?
    if [ $rc != 0 ]; then
        echo "$mod NOT RUNNING (process $pid doesn't exist ?)"
        return 1
    fi
    echo "$mod RUNNING (pid $pid)"
    return 0
}

#
# start our modules
#
do_start() {
    mod=$1
    modfilepath="$BIN/shinken-${mod}"
    [ -e "$modfilepath" ] || {
    	echo "FAILED: did not found $mod file ($modfilepath) ; are you sure shinken-$mod is installed ?"
    	return 5
    }
    [ "$DEBUG" = 1 ] && DEBUGCMD="--debug $VAR/${mod}-debug.log"
    if [ "$mod" != "arbiter" ]; then
        output=$("$modfilepath" -d -c "$ETC/${mod}d.ini" $DEBUGCMD 2>&1)
        rc=$?
    else
        output=$("$modfilepath" -d -c "$ETC/nagios.cfg" -c "$ETC/shinken-specific.cfg" $DEBUGCMD 2>&1)
        rc=$?
    fi
    if [ $rc != 0 ]; then
        output=$(echo "$output" | tail -1)
        echo "FAILED: $output"
        return 1
    fi
    echo "OK"
    return 0
}

#
# stop modules
#
do_stop() {
    mod=$1
    pid=$(getmodpid "$mod")
    statusoutput=$(do_status "$mod")
    [ $? -ne 0 ] && {
        echo "$statusoutput"
        return 0
    }
    if [ ! -z "$pid" ]; then
        for cpid in $(ps -aef | grep "$pid" | grep "shinken-$mod" | awk '{print $2}'); do
            kill $cpid > /dev/null 2>&1
        done
        sleep 1
        ## TODO: instead of 'sleep 1' : wait up to when pid file is removed (with timeout) ?
        pid=$(getmodpid $mod)
        if [ ! -z "$pid" ]; then
            allpids="$(ps -aef | grep "$pid" | grep "shinken-$mod" | awk '{print $2}')"
            ## TODO: we could 'kill -9' the remaining processes.. if we are sure they are the good one..
            if [ ! -z "$allpids" ]; then
                echo "FAILED: one or more process for $mod are still running after kill !"
                echo "Remaining processes are (pids="$allpids"):"
                ps -lf $(for p in $allpids ; do echo -n "-p$p " ; done)
                echo "You should maybe check and see this." 
                return 1
            fi
        fi
        echo "OK"
    else
        echo "NOT RUNNING"
    fi
    return 0
}

#
# do the config check
#
do_check() {
    [ "$DEBUG" = 1 ] && DEBUGCMD="--debug $VAR/${mod}-debug.log"
    "$BIN/shinken-arbiter" -v -c "$ETC/shinken-specific.cfg" $DEBUGCMD 2>&1
    return $?
}


############################

do_start_() {
    log_daemon_msg "Starting $1"
    status=$(do_status "$1")
    rc=$?
    if [ $rc -eq 0 ]; then
        log_success_msg "Already running"
        log_end_msg 0
        return
    fi
    startoutput=$(do_start "$1")
    rc=$?
    if [ $rc -eq 0 ]; then
        log_end_msg 0 
    else
        log_failure_msg  "$startoutput" 
        log_end_msg 1
    fi
    return $rc
}

do_stop_() {
    log_daemon_msg "Stopping $1"
    statusoutput=$(do_status "$1")
    rc=$?
    if [ $rc -ne 0 ]; then
        failuremsg="Couldn't get status of $1 : $statusoutput"
    else
        stopoutput=$(do_stop "$1" 2>&1)
        rc=$?
        [ $rc -ne 0 ] && failuremsg="Couldn't stop $1 : $stopoutput"
    fi
    if [ $rc -ne 0 ]; then
        log_failure_msg "$failuremsg"
        log_end_msg 1
    else
        log_end_msg 0
    fi
    return $rc
}

do_restart_() {
    log_daemon_msg "Restarting $1"
    stopoutput=$(do_stop "$1")
    startoutput=$(do_start "$1")
    rc=$?
    if [ $rc -eq 0 ]; then
        log_end_msg 0
    else
        log_failure_msg "$startoutput"
        log_end_msg 1
    fi
    return $rc
}

do_status_() {
    mod=$1
    log_daemon_msg "Checking status of $mod"
    do_status "$1"
    log_end_msg $?
}

do_check_() {
    log_daemon_msg "Doing config check"
    output=$(do_check "$1" 2>&1)
    rc=$?
    if [ $rc -eq 0 ]; then
        log_end_msg 0
    else
        log_end_msg 1
    fi
    return $rc
}
do_checkconfig_() { do_check_ "$1" ; }


############################

do_cmd_on() {
    action=$1
    mods=$2
    for mod in $mods
    do
        do_${action}_ "$mod"
    done
}


############################
## Main:

case "$CMD" in
	start|stop|restart|status)
		do_cmd_on "$CMD" "$SUBMODULES"
    	;;
	check|checkconfig)
		do_cmd_on "$CMD" "arbiter"
		;;
	*)
    	usage >&2
    	exit 2
    	;;
esac
