#!/bin/bash

# chkconfig: 345 99 01
# description: Blackbox Exporter

### BEGIN INIT INFO
# Provides:       blackbox_exporter
# Required-Start: 
# Required-Stop:  
# Default-Start:  2 3 5
# Default-Stop:
# Description:    Blackbox Exporter
### END INIT INFO

# Author: Gerhard Lausser <gerhard.lausser@consol.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.
#   - When a service is already running and should be started
#     this also should result in an exit code of 0.
# - 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 /omd/sites/monitor
. .profile
. lib/omd/init_profile
. etc/omd/site.conf
[ "$CONFIG_BLACKBOX_EXPORTER" = "on" ] || exit 5

mkdir -p /omd/sites/monitor/tmp/blackbox_exporter
mkdir -p /omd/sites/monitor/var/blackbox_exporter
BIN=/omd/sites/monitor/bin/blackbox_exporter
TOOL=/omd/sites/monitor/bin/promtool # a smiliar tool for the blackbox_exporter does not yet exist
CFG_FILE=/omd/sites/monitor/tmp/blackbox_exporter/blackbox_exporter.yml
LOG_DIR=/omd/sites/monitor/var/blackbox_exporter
LOGFILE=/omd/sites/monitor/var/blackbox_exporter/blackbox_exporter.log
PID_FILE=/omd/sites/monitor/tmp/lock/blackbox_exporter.lock
DATA_DIR=/omd/sites/monitor/var/blackbox_exporter/data
USR=monitor
GRP=monitor

unset LANG
export LC_ALL=C

# OMD: create configuration file out of fragments
case "$1" in start|restart|reload|checkconfig|check)
    #merge-blackbox_exporter-config \
    #   /omd/sites/monitor/etc/blackbox_exporter/blackbox_exporter.d/*.yml \
    #   /omd/sites/monitor/etc/blackbox_exporter/blackbox_exporter.yml \
    #   > $CFG_FILE || rm -f $CFG_FILE 
    cat \
       /omd/sites/monitor/etc/blackbox_exporter/blackbox_exporter.yml \
       > $CFG_FILE
    for y in /omd/sites/monitor/etc/blackbox_exporter/blackbox_exporter.d/*.yml
    do
       test -f $y && cat $y >> $CFG_FILE
    done
    sed -ri "s/###BLACKBOX_EXPORTER_TCP_PORT###/$CONFIG_BLACKBOX_EXPORTER_TCP_PORT/g" $CFG_FILE
    sed -ri "s/###BLACKBOX_EXPORTER_TCP_ADDR###/$CONFIG_BLACKBOX_EXPORTER_TCP_ADDR/g" $CFG_FILE
esac

OPTIONS="--config.file $CFG_FILE --web.listen-address=$CONFIG_BLACKBOX_EXPORTER_TCP_ADDR:$CONFIG_BLACKBOX_EXPORTER_TCP_PORT"

# Fetches the pid of the currently running blackbox_exporter 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.
blackbox_exporter_proc() {
    PID=$(pgrep -u $USR -o -fx "$BIN $OPTIONS" 2>/dev/null)
    #PROC=$(ps -u $USR --ppid 1 -o pid,ppid,cmd \
    #         | grep "$BIN $OPTIONS" 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 blackbox_exporter 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_blackbox_exporter() {
    blackbox_exporter_proc
    return $?
}


verify_config() {
    if [ "$1" != "quiet" ]; then
        echo -n "Running configuration check... "
    fi
    RESULT=$($TOOL check-config $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 Blackbox Exporter configuration."
        fi
        echo "$RESULT" >&2
        return 1
    fi
}

prep_start() {
    touch $PID_FILE
    chown $USR:$GRP $PID_FILE
}

blackbox_exporter_wait_stop() {
    pid=$(pidof_blackbox_exporter) || 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 blackbox_exporter has a subprocess which
    # is left running and becomes ppid 1 after killing the
    # main blackbox_exporter 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_blackbox_exporter | head -n1) || true
        done
    fi

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

}

blackbox_exporter_wait_start() {
    prep_start
    nohup $BIN $OPTIONS >>$LOGFILE 2>&1 &
    I=0
    while ! pidof_blackbox_exporter >/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 "Blackbox Exporter binary $BIN not found. Terminating..."
    exit 1
fi

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

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

         #if ! verify_config quiet; then
         #    exit 1
         #fi

         if blackbox_exporter_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 blackbox_exporter..."
        if blackbox_exporter_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_blackbox_exporter 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 Blackbox Exporter. Terminating..." && exit 1)
        echo -n "Starting Blackbox Exporter..."
        if blackbox_exporter_wait_start; then
            echo 'OK'
            exit 0
        else
            echo 'ERROR'
            exit 1
        fi
    ;;
    
    reload|force-reload)
        $0 restart
    ;;
    check)
    ;;
    *)
        echo "Usage: blackbox_exporter {start|stop|restart|reload|status|checkconfig}"
        exit 2
    ;;
esac
 
# EOF
