#!/bin/sh
### BEGIN INIT INFO
# Provides:          grafana
# Required-Start:    $remote_fs
# Required-Stop:     $remote_fs
# Should-Start:      $syslog
# Should-Stop:       $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Start grafana at boot time
# Description: Grafana - feature rich metrics dashboard and graph editor
### END INIT INFO

NAME=$(basename $(readlink -f $0))
DAEMON=/usr/sbin/$NAME
PIDFILE=/var/run/$NAME.pid

# Exit if executable is not installed
[ -x "$DAEMON" ] || exit 0

umask 0027
if [ "$(id -u)" -ne 0 ]; then
    echo "You need root privileges to run this script"
    exit 1
fi

DAEMON_USER=grafana
DAEMON_GROUP=grafana
WORK_DIR=/usr/share/grafana
CONF_FILE=/etc/grafana/grafana.ini
DATA_DIR=/var/lib/grafana
LOG_DIR=/var/log/grafana
MAX_OPEN_FILES=10000

# Read configuration variable file if it is present
[ -r /etc/default/$NAME ] && . /etc/default/$NAME

DAEMON_ARGS="--config=${CONF_FILE} cfg:default.paths.data=${DATA_DIR} cfg:default.paths.logs=${LOG_DIR}"

RETRY=TERM/30/KILL/5

# Load the VERBOSE setting and other rcS variables
[ -f /etc/default/rcS ] && . /etc/default/rcS

# Define LSB log_* functions.
. /lib/lsb/init-functions

_ev_ () {
  local rv_=$?
  [ "$VERBOSE" = "no" ] || eval $@
  return $rv_
}

case "$1" in
    start)
        if [ -n "$MAX_OPEN_FILES" ]; then
            ulimit -n $MAX_OPEN_FILES || true
        fi
        _ev_ log_action_begin_msg \"Starting $NAME\"
        if R=$($0 status); then
            _ev_ log_action_end_msg 0 \"$R\"
        else
            R=$(start-stop-daemon --start --pidfile $PIDFILE --make-pidfile --background \
                --chuid $DAEMON_USER --chdir "$WORK_DIR" \
                --exec $DAEMON \
                -- $DAEMON_ARGS)
            sleep 1
            $0 status >>/dev/null
            _ev_ log_action_end_msg $? \"$R\"
        fi
    ;;
    stop)
        _ev_ log_action_begin_msg \"Stopping $NAME\"
        R=$(start-stop-daemon --stop --oknodo --user $DAEMON_USER --pidfile $PIDFILE --remove-pidfile --retry=$RETRY 2>&1)
        _ev_ log_action_end_msg $? \"$R\"
    ;;
    status)
        ## return status 0 if process is running.
        status_of_proc -p $PIDFILE "$DAEMON" "$NAME"
    ;;
    restart|force-reload)
        $0 stop
        $0 start
    ;;
    *)
        log_action_msg "Usage: /etc/init.d/$NAME {start|stop|restart|force-reload|status}"
    ;;
esac
