#!/bin/bash

# chkconfig: 345 99 01
# description: Pushgateway Pushgateway

### BEGIN INIT INFO
# Provides:       pushgateway
# Required-Start: 
# Required-Stop:  
# Default-Start:  2 3 5
# Default-Stop:
# Description: Pushgateway Pushgateway
### 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_PUSHGATEWAY" = "on" ] || exit 5

mkdir -p /omd/sites/monitor/tmp/pushgateway
mkdir -p /omd/sites/monitor/var/pushgateway/data
BIN=/omd/sites/monitor/bin/pushgateway
LOG_DIR=/omd/sites/monitor/var/pushgateway
LOGFILE=/omd/sites/monitor/var/pushgateway/pushgateway.log
PID_FILE=/omd/sites/monitor/tmp/lock/pushgateway.lock
DATA_DIR=/omd/sites/monitor/var/pushgateway/data
USR=monitor
GRP=monitor

EXTERNAL_FQDN=${OMD_EXTERNAL_FQDN:-$(hostname --fqdn)}

unset LANG
export LC_ALL=C

OPTIONS="--persistence.file=$DATA_DIR/persistence --web.listen-address=$CONFIG_PUSHGATEWAY_TCP_ADDR:$CONFIG_PUSHGATEWAY_TCP_PORT"

# Fetches the pid of the currently running pushgateway 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.
pushgateway_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 pushgateway 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_pushgateway() {
    pushgateway_proc
    return $?
}


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

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

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

}

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

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

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

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