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

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

DAEMON=/usr/bin/postgres_exporter
NAME=postgres_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
    chown -R "$NAME:$NAME" "$(dirname "$LOGFILE")"
}

do_start_cmd()
{
    do_start_prepare
    echo -n "Starting daemon: $NAME"
    daemon --user "$NAME" --pidfile "$PIDFILE" --check "$NAME" "$DAEMON $ARGS >> $LOGFILE 2>&1 &"
    sleep 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
