#!/usr/bin/env bash

# description: Grafana loki server

# Check if grafana-loki is enabled in OMD. If not terminate.
. lib/omd/init_profile
. etc/omd/site.conf
if [ "$CONFIG_LOKI" != "on" ] ; then
    exit 5
fi

NAME="Loki"
CONF_DIR=$OMD_ROOT/etc/loki
LOG_DIR=$OMD_ROOT/var/log
CONF_FILE=$CONF_DIR/loki.yaml
PID_FILE=$OMD_ROOT/tmp/run/$NAME.pid
LOGFILE=$LOG_DIR/loki.log
DATA_DIR=$OMD_ROOT/var/loki
DAEMON=$OMD_ROOT/bin/loki

OPTIONS="-config.file=${CONF_FILE}"

get_status() {
    pid=$( cat $PID_FILE 2>/dev/null )
    if [ -n "$pid" ]; then
        if ps -p $pid > /dev/null 2>&1 ; then
            echo "$NAME is running with pid $pid"
            return 0;
        fi
    fi
    echo "$NAME is not running"
    return 1;
}

stop_loki() {
    pid=$( cat $PID_FILE 2>/dev/null )
    if [ -z "$pid" ]; then
        echo ". Not running."
    else
        ps -p $pid > /dev/null 2>&1 && kill $pid
        for x in $(seq 15); do
            printf "."
            ps -p $pid > /dev/null 2>&1 || break
            sleep 0.2;
        done
        if ! ps -p $pid > /dev/null 2>&1 ; then
            echo "OK"
            __init_hook $0 $1 post 0
            exit 0;
        else
            echo "failed"
            __init_hook $0 $1 post 1
            exit 1;
        fi
    fi
}

__init_hook $0 $1 pre
case "$1" in
  start)
        printf '%s' "Starting $NAME..."

        if get_status > /dev/null ; then
            echo "failed"
            echo "$NAME already running"
            exit 0;
        fi

        mkdir -p "$LOG_DIR" "$DATA_DIR"
        touch "$PID_FILE"
        nohup $DAEMON $OPTIONS >>$LOGFILE 2>&1 &
        if [ $? -eq 0 ]; then
            echo "OK"
            echo "$!" > $PID_FILE
            __init_hook $0 $1 post 0
            exit 0;
        else
            echo "failed"
            __init_hook $0 $1 post 1
            exit 1;
        fi
    ;;
  stop)
        printf '%s' "Stopping $NAME..."
        pid=$( cat $PID_FILE 2>/dev/null )
        if [ -z "$pid" ]; then
            echo ". Not running."
        else
            stop_loki;
        fi
    ;;
  status)
        get_status;
        exit $?;
    ;;
    reload|restart)
        $0 stop && sleep 1 && $0 start
        exit $?
    ;;
  check)
    ;;
  *)
        echo "Usage: $NAME {start|stop|kill|status|restart}"
        exit 1
    ;;
esac

exit 0
