#!/bin/bash
### BEGIN INIT INFO
# Provides:          carbon-cache
# Required-Start:    $remote_fs $syslog
# Required-Stop:     $remote_fs $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Carbon Cache
# Description:       Carbon Cache
### END INIT INFO

CARBON_DAEMON="cache"
NAME="carbon-${CARBON_DAEMON}"

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

# Load the VERBOSE setting and other rcS variables
. /lib/init/vars.sh

# Define LSB log_* functions.
# Depend on lsb-base (>= 3.0-6) to ensure that this file is present.
. /lib/lsb/init-functions

INSTANCES=`grep "^\[${CARBON_DAEMON}" /etc/graphite/carbon.conf | cut -d \[ -f 2 | cut -d \] -f 1 | cut -d : -f 2`

function die {
  echo $1
  exit 1
}

start(){
    for INSTANCE in ${INSTANCES}; do
        if [ "${INSTANCE}" == "${CARBON_DAEMON}" ]; then
            INSTANCE="a";
        fi;
        echo "Starting carbon-${CARBON_DAEMON}:${INSTANCE}..."
        /usr/local/bin/carbon-${CARBON_DAEMON}.py --config /etc/graphite/carbon.conf --instance=${INSTANCE} start;

        if [ $? -eq 0 ]; then
            echo "success"
        else
            echo "failure"
        fi;
        echo ""
    done;
}

stop(){
    for INSTANCE in ${INSTANCES}; do
        if [ "${INSTANCE}" == "${CARBON_DAEMON}" ]; then
            INSTANCE="a";
        fi;
        echo "Stopping carbon-${CARBON_DAEMON}:${INSTANCE}..."
        /usr/local/bin/carbon-${CARBON_DAEMON}.py --config /etc/graphite/carbon.conf --instance=${INSTANCE} stop

        if [ `sleep 3; /usr/bin/pgrep -f "carbon-${CARBON_DAEMON}.py --instance=${INSTANCE}" | /usr/bin/wc -l` -gt 0 ]; then
            echo "Carbon did not stop yet. Sleeping longer, then force killing it...";
            sleep 20;
            /usr/bin/pkill -9 -f "carbon-${CARBON_DAEMON}.py --instance=${INSTANCE}";
        fi;

        if [ $? -eq 0 ]; then
            echo "success"
        else
            echo "failure"
        fi;
        echo ""
    done;
}

status(){
    for INSTANCE in ${INSTANCES}; do
        if [ "${INSTANCE}" == "${CARBON_DAEMON}" ]; then
            INSTANCE="a";
        fi;
        /usr/local/bin/carbon-${CARBON_DAEMON}.py --config /etc/graphite/carbon.conf --instance=${INSTANCE} status;
    done;
}

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