#!/bin/bash

# chkconfig: 345 99 01
# description: Icinga network monitoring daemon

### BEGIN INIT INFO
# Provides:       icinga
# Required-Start: 
# Required-Stop:  
# Default-Start:  2 3 5
# Default-Stop:
# Description:    Icinga network monitoring daemon
### END INIT INFO

# Author: Lars Michelsen <lm@mathias-kettner.de>
# Changes for Icinga: Bastian Kuhn <mail@bastian-kuhn.de>

# Notes for OMD init script requirements
# - Must handle omd config options like daemon enabling/disabling
# - When a daemon is disabled by omd config it needs
#   to return an exit code of 5.
# - The init script must output an exit code of 2 when
#   an unknown param is used.
# - In general the exit code for succeeded actions is
#   0 and for failed actions it is 1.
# - There are exceptions for the exit code handling:
#   - When a service is already stopped and should be
#     restarted/stopped, it should result in an exit code of 0.
#   - FIXME: What if a service should be started and is already started?
# - When a restart is requested and the program is still not running
#   the script should only execute a start
# - When a restart is requested and the program can not be stopped the
#   script should terminate without starting the daemon
# - When a reload is requested and the program is not running
#   the init script should execute a start instead

cd ###ROOT###
. .profile
. lib/omd/init_profile
. etc/omd/site.conf
[ "$CONFIG_CORE" = "icinga" ] || exit 5

BIN=###ROOT###/bin/icinga
CFG_FILE=###ROOT###/tmp/icinga/icinga.cfg
STATUS_FILE=###ROOT###/tmp/icinga/status.dat
CMD_FILE=###ROOT###/tmp/run/icinga.cmd
PID_FILE=###ROOT###/tmp/lock/icinga.lock
STATUS_DAT=###ROOT###/tmp/icinga/status.dat
USR=###SITE###
GRP=###SITE###

# OMD: create configuration file out of fragments
case "$1" in start|restart|reload|checkconfig|check)
    merge-icinga-config \
       ###ROOT###/etc/icinga/icinga.d/*.cfg \
       ###ROOT###/etc/icinga/icinga.cfg \
       > $CFG_FILE || rm -f $CFG_FILE 
    if [ $? -ne 0 ]; then exit 1; fi
esac

OPTIONS="-ud"

# Fetches the pid of the currently running nagios process of the given
# user.
#
# --ppid 1 in ps seem not to filter by direct ppid but by the whole
# parent process tree. So filter by hand again.
# 
# It returns 1 when no process can be found and echos the PID while
# returning 0 when a process can be found.
nagios_proc() {
    PROC=$(ps -u $USR --ppid 1 -o pid,ppid,cmd \
             | grep "$BIN $OPTIONS $CFG_FILE" 2>&1 | grep ' 1 ' | grep -v grep)
    PID=$(echo "$PROC" | sed 's/^ *//g' | cut -d' ' -f1)
    if [ "$PID" != "" ]; then
        echo "$PID"
        return 0
    else
        return 1
    fi
}

# First try to use the process list to gather a nagios process,
# when no process is found via ps take a look at the lock file
#
# It returns 1 when no process can be found and echos the PID while
# returning 0 when a process can be found.
pidof_nagios() {
    nagios_proc
    return $?
}

verify_config() {
    if [ "$1" != "quiet" ]; then
        echo -n "Running configuration check... "
    fi
    RESULT=$($BIN -pv $CFG_FILE 2>&1)
    if [ $? -eq 0 ]; then
        if [ "$1" != "quiet" ]; then
            echo "done."
            echo "$RESULT" >&2
        fi
        return 0
    else
        if [ "$1" != "quiet" ]; then
            echo "CONFIG ERROR! Aborted. Check your Icinga configuration."
        fi
        echo "$RESULT" >&2
        return 1
    fi
}

prep_start() {
    if [ -f $CMD_FILE ]; then
        rm -f $CMD_FILE
    fi
    touch $PID_FILE
    chown $USR:$GRP $PID_FILE
}

nagios_wait_stop() {
    pid=$(pidof_nagios) || true
    if ! kill -0 "${pid:-}" >/dev/null 2>&1; then
        echo -n 'Not running. '
        return 0
    fi

    # wait until really stopped.
    # it might happen that nagios has a subprocess which
    # is left running and becomes ppid 1 after killing the
    # main nagios process. So fetch the process id again
    # multiple times to fetch new processes until all are gone.
    if [ -n "${pid:-}" ]; then
        I=0
        while kill -0 ${pid:-} >/dev/null 2>&1; do
            # Send single kill per process
            kill $pid
            while kill -0 ${pid:-} >/dev/null 2>&1;  do
                if [ $I = '60' ]; then
                    return 1
                else
                    echo -n "."
                    I=$(($I+1))
                    sleep 1
                fi
            done
            # Is there another proc with ppid 1?
            pid=$(pidof_nagios | head -n1) || true
        done
    fi

    [ -f "$PID_FILE" ] && rm -f "$PID_FILE"
    return 0
}

nagios_wait_start() {
    prep_start
    $BIN $OPTIONS $CFG_FILE

    I=0
    while ! pidof_nagios >/dev/null 2>&1;  do
        if [ $I = '10' ]; then
            return 1
        else
            echo -n "."
            I=$(($I+1))
            sleep 1
        fi
    done

    return 0
}

if [ ! -f $BIN ]; then
    echo "Icinga binary $BIN not found. Terminating..."
    exit 1
fi

case "$1" in start|restart|reload|checkconfig)
    if [ ! -f $CFG_FILE ]; then
        echo "Icinga configuration file $CFG_FILE not found. Terminating..."
        exit 1
    fi
esac

__init_hook $0 $1 pre
case "$1" in
    start)
         echo -n "Starting icinga..."
         if pidof_nagios >/dev/null 2>&1; then
             echo 'Already running.'
             exit 1
         fi

         if ! verify_config quiet; then
             exit 1
         fi

         if nagios_wait_start; then
             echo 'OK'
             __init_hook $0 $1 post 0
             exit 0
         else
             echo 'ERROR'
             __init_hook $0 $1 post 1
             exit 1
         fi
    ;;
    stop)
        echo -n "Stopping icinga..."
        if nagios_wait_stop; then
            echo 'OK'
             __init_hook $0 $1 post 0
            exit 0
        else
            echo 'ERROR'
             __init_hook $0 $1 post 1
            exit 1
        fi
    ;;
    check|checkconfig)
        if ! verify_config; then
            exit 1
        fi
        exit 0
    ;;
    status)
        PID=$(pidof_nagios 2>&1) || true
        if kill -0 "${PID:-}" >/dev/null 2>&1; then
            echo "Running ($PID)."
            exit 0
        else
            echo 'Not running. '
            exit 1
        fi
    ;;
    restart)
        if ! verify_config quiet; then
            exit 1
        fi

        $0 stop || (echo "Unable to stop icinga. Terminating..." && exit 1)
        echo -n "Starting icinga..."
        if nagios_wait_start; then
            echo 'OK'
            exit 0
        else
            echo 'ERROR'
            exit 1
        fi
    ;;

    reload|force-reload)
        if ! verify_config quiet; then
            exit 1
        fi

        # Execute a start when nagios is not running
        if ! pidof_nagios >/dev/null 2>&1; then
            $0 start
            exit $?
        fi

        echo -n "Reloading icinga configuration (PID: $PID)... "
        if kill -HUP ${PID:-} >/dev/null 2>&1; then
            echo 'OK'
            __init_hook $0 $1 post 0
            exit 0
        else
            $0 restart
            exit $?
        fi
    ;;

    *)
        echo "Usage: icinga {start|stop|restart|reload|status|checkconfig}"
        exit 2
    ;;
esac

# EOF
