#!/bin/sh
### BEGIN INIT INFO
# Provides:          Blackbox exporter metrics for prometheus
# 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
# Description:       Blackbox exporter for prometheus written in Go
### END INIT INFO

# Source function library.
. /etc/rc.d/init.d/functions

DAEMON=/usr/bin/blackbox_exporter
NAME=blackbox_exporter
PIDFILE=/var/run/$NAME.pid
LOGFILE=/var/log/$NAME/$NAME.log

ARGS=""
[ -r /etc/sysconfig/$NAME ] && . /etc/sysconfig/$NAME

do_start_prepare()
{
    mkdir -p `dirname $LOGFILE` || true
}

do_start_cmd()
{
    do_start_prepare
    echo -n $"Starting daemon: $NAME"
    daemon --pidfile $PIDFILE --check "$NAME" "$DAEMON $ARGS >> $LOGFILE 2>&1 &"
    PID=$(pidof $DAEMON)
    if [ -z $PID ]; then
        exit 7
    else
        echo $PID > $PIDFILE
    fi
    echo
}

do_stop_cmd()
{
    echo -n "Stopping daemon: "$NAME
    killproc -p $PIDFILE -d 10 $NAME
    echo
}

status() {
    printf "%-50s" "Checking $NAME..."
    if [ -f $PIDFILE ]; then
        PID=$(cat $PIDFILE)
            if [ -z "$(ps axf | grep ${PID} | grep -v grep)" ]; then
                printf "%s\n" "The process appears to be dead but pidfile still exists"
            else
                echo "Running, the PID is $PID"
            fi
    else
        printf "%s\n" "Service not running"
    fi
}

case "$1" in
  start)
    do_start_cmd
    ;;
  stop)
    do_stop_cmd
    ;;
  status)
    status
    ;;
  restart)
    do_stop_cmd
    do_start_cmd
    ;;
  *)
    echo "Usage: $1 {start|stop|status|restart|uninstall}"
    exit 1
esac

exit 0
