#!/bin/bash

### BEGIN INIT INFO
# Provides:          influxdb
# Required-Start:    $network $local_fs $remote_fs
# Required-Stop:     $network $local_fs $remote_fs $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: InfluxDB is an open-source, distributed, time series database
# Description:       InfluxDB is a time series, metrics, and analytics database.
#                    It’s written in Go and has no external dependencies. That
#                    means once you install it there’s nothing else to manage
#                    (such as Redis, ZooKeeper, Cassandra, HBase, or anything
#                    else). InfluxDB is targeted at use cases for DevOps,
#                    metrics, sensor data, and real-time analytics.
### END INIT INFO

# If you modify this, please make sure to also edit influxdb.service
# this init script supports three different variations:
#  1. New lsb that define start-stop-daemon
#  2. Old lsb that don't have start-stop-daemon but define, log, pidofproc and killproc
#  3. Centos installations without lsb-core installed
#
# In the third case we have to define our own functions which are very dumb
# and expect the args to be positioned correctly.

# Command-line options that can be set in /etc/default/influxdb.  These will override
# any config file values. Example: "-join http://1.2.3.4:8086"
INFLUXD_OPTS=

USER=influxdb
GROUP=influxdb

if [ -r /lib/lsb/init-functions ]; then
    source /lib/lsb/init-functions
fi

DEFAULT=/etc/default/influxdb

if [ -r $DEFAULT ]; then
    source $DEFAULT
fi

if [ -z "$STDOUT" ]; then
    STDOUT=/dev/null
fi
if [ ! -f "$STDOUT" ]; then
    mkdir -p $(dirname $STDOUT)
fi

if [ -z "$STDERR" ]; then
    STDERR=/var/log/influxdb/influxd.log
fi
if [ ! -f "$STDERR" ]; then
    mkdir -p $(dirname $STDERR)
fi


OPEN_FILE_LIMIT=65536

function pidofproc() {
    if [ $# -ne 3 ]; then
        echo "Expected three arguments, e.g. $0 -p pidfile daemon-name"
    fi

    pid=$(pgrep -f $3)
    local pidfile=$(cat $2)

    if [ "x$pidfile" == "x" ]; then
        return 1
    fi

    if [ "x$pid" != "x" -a "$pidfile" == "$pid" ]; then
        return 0
    fi

    return 1
}

function killproc() {
    if [ $# -ne 3 ]; then
        echo "Expected three arguments, e.g. $0 -p pidfile signal"
    fi

    PID=`cat $2`

    /bin/kill -s $3 $PID
    while true; do
        pidof `basename $daemon` >/dev/null
        if [ $? -ne 0 ]; then
            return 0
        fi

        sleep 1
        n=$(expr $n + 1)
        if [ $n -eq 30 ]; then
            /bin/kill -s SIGKILL $PID
            return 0
        fi
    done
}

# Process name ( For display )
name=influxd
desc=database

# Daemon name, where is the actual executable
daemon=/usr/bin/influxd

# pid file for the daemon
pidfile=/var/run/influxdb/influxd.pid
piddir=$(dirname $pidfile)

if [ ! -d "$piddir" ]; then
    mkdir -p $piddir
    chown $USER:$GROUP $piddir
fi

# Configuration file
config=/etc/influxdb/influxdb.conf

# If the daemon is not there, then exit.
[ -x $daemon ] || exit 0

function wait_for_startup() {
    control=1
    while [ $control -lt 5 ]
    do
        if [ ! -e $pidfile ]; then
            sleep 1
            control=$((control+1))
        else
            break
        fi
    done
}

function is_process_running() {
    # Checked the PID file exists and check the actual status of process
    if [ -e $pidfile ]; then
        pidofproc -p $pidfile $daemon > /dev/null 2>&1 && status="0" || status="$?"
        # If the status is SUCCESS then don't need to start again.
        if [ "x$status" = "x0" ]; then
            return 0
        else
            return 1
        fi
    else
        return 1
    fi
}

case $1 in
    start)
        log_daemon_msg "Starting $desc" "$name"

        # Check if it's running first
        is_process_running
        if [ $? -eq 0 ]; then
            log_end_msg 0
            exit 0
        fi

        # Bump the file limits, before launching the daemon. These will carry over to
        # launched processes.
        ulimit -n $OPEN_FILE_LIMIT
        if [ $? -ne 0 ]; then
            log_progress_msg "set open file limit to $OPEN_FILE_LIMIT"
            log_end_msg 1
            exit 1
        fi

        if which start-stop-daemon > /dev/null 2>&1; then
            start-stop-daemon --chuid $GROUP:$USER --start --quiet --pidfile $pidfile --exec $daemon -- -pidfile $pidfile -config $config $INFLUXD_OPTS >>$STDOUT 2>>$STDERR &
        else
            su $USER -c "nohup $daemon -pidfile $pidfile -config $config $INFLUXD_OPTS >>$STDOUT 2>>$STDERR &"
        fi

        wait_for_startup && is_process_running
        if [ $? -ne 0 ]; then
            log_progress_msg "$name process failed to start"
            log_end_msg 1
            exit 1
        else
            log_end_msg 0
            exit 0
        fi
        ;;

    stop)
        log_daemon_msg "Stopping $desc" "$name"

        # Stop the daemon.
        is_process_running
        if [ $? -ne 0 ]; then
            log_progress_msg "$name process is not running"
            log_end_msg 0
            exit 0 # Exit
        else
            if killproc -p $pidfile SIGTERM && /bin/rm -rf $pidfile; then
                log_end_msg 0
                exit 0
            else
                log_end_msg 1
                exit 1
            fi
        fi
        ;;

    restart|force-reload)
        log_daemon_msg "Restarting $desc" "$name"
        # Restart the daemon.
        $0 stop && sleep 2 && $0 start
        $0 status || errcode=$?
        log_end_msg $errcode
        ;;

    status)
        log_daemon_msg "Checking status of $desc" "$name"

        # Check the status of the process.
        is_process_running
        if [ $? -eq 0 ]; then
            log_progress_msg "running"
            log_end_msg 0
            exit 0
        else
            log_progress_msg "apparently not running"
            log_end_msg 1
            exit 1
        fi
        ;;

    version)
        $daemon version
        ;;

    *)
        # For invalid arguments, print the usage message.
        echo "Usage: $0 {start|stop|restart|status|version}"
        exit 2
        ;;
esac
