#!/bin/sh

### BEGIN INIT INFO
# Provides: monasca-agent
# Short-Description: Start and start monasca-agent
# Description: monasca-agent is the monitoring Agent component OpenStack Monitoring
# Required-Start: $remote_fs
# Required-Stop: $remote_fs
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
### END INIT INFO

PATH=$PATH:/usr/local/bin # supervisord might live here
PATH=$PATH:/sbin

AGENTPATH="{prefix}/bin/monasca-collector"
AGENTCONF="{config_dir}/agent.yaml"
MONASCASTATSDPATH="{prefix}/bin/monasca-statsd"
AGENTUSER="{monasca_user}"
FORWARDERPATH="{prefix}/bin/monasca-forwarder"
NAME="monasca-agent"
DESC="Monasca Monitoring Agent"
AGENT_PID_PATH="/var/tmp/monasca-agent.pid"
SUPERVISOR_PIDFILE="/var/tmp/monasca-agent-supervisord.pid"
SUPERVISOR_FILE="{config_dir}/supervisor.conf"
SUPERVISOR_SOCK="/var/tmp/monasca-agent-supervisor.sock"
SUPERVISORD="{prefix}/bin/supervisord"
SUPERVISORCTL="{prefix}/bin/supervisorctl"

# This script is considered a configuration file and will not be
# removed by dpkg unless the --purge option it set. Therefore we
# make sure that the Agent is actually installed before we try to do anything:
if [ ! -x $AGENTPATH ]; then
    echo "$AGENTPATH not found. Exiting."
    exit 0
fi

check_status() {{
    # If the socket exists, we can use supervisorctl
    if [ -e $SUPERVISOR_SOCK ]; then
        # If we're using supervisor, check the number of processes
        # supervisor is currently controlling, and make sure that it's the
        # same as the number of programs specified in the supervisor config
        # file:

        supervisor_processes=$($SUPERVISORCTL -c $SUPERVISOR_FILE status)
        supervisor_processes=$(echo "$supervisor_processes" |
                                       grep -v pup |
                                       grep $NAME |
                                       grep -c RUNNING)
        supervisor_config_programs=$(grep -v pup $SUPERVISOR_FILE |
                                     grep -c '\[program:')

        if [ "$supervisor_processes" -ne "$supervisor_config_programs" ]; then
            echo "$supervisor_processes"
            echo "$DESC (supervisor) is NOT running all child processes"
            return 1
        else
            echo "$DESC (supervisor) is running all child processes"
            return 0
        fi
    else
        echo "$DESC (supervisor) is not running"
        return 1
    fi
}}

# Action to take
case "$1" in
    start)
        if [ ! -f $AGENTCONF ]; then
            echo "$AGENTCONF not found. Exiting."
            exit 3
        fi

        check_status > /dev/null
        if [ $? -eq 0 ]; then
            echo "$DESC is already running"
            exit 0
        fi

        su $AGENTUSER -c "$AGENTPATH configcheck" > /dev/null
        if [ $? -ne 0 ]; then
            echo "Invalid check configuration. Please run sudo /etc/init.d/monasca-agent configtest for more details."
            echo "Resuming starting process."
        fi


        echo "Starting $DESC (using supervisord)" "$NAME"
        $SUPERVISORD -c $SUPERVISOR_FILE -u $AGENTUSER --pidfile $SUPERVISOR_PIDFILE
        if [ $? -ne 0 ]; then
            exit $?
        fi

        # check if the agent is running once per second for 10 seconds
        retries=10
        while [ $retries -gt 1 ]; do
          if check_status > /dev/null; then
              # We've started up successfully. Exit cleanly
              exit 0
          else
              retries=$(($retries - 1))
              sleep 1
          fi
        done
        # After 10 tries the agent didn't start. Report an error
        exit 1
        check_status # report what went wrong
        $0 stop
        exit 1
        ;;
    stop)

        if [ -e $SUPERVISOR_PIDFILE ]; then
            kill `cat $SUPERVISOR_PIDFILE`
            retries=10
            until ! check_status > /dev/null; do
                if [ $retries -le 1 ]; then
                    echo "Timeout hit while waiting for agent to stop"
                    break
                else
                    retries=$(($retries - 1))
                    sleep 1
                fi
            done
        else
            echo "Pid file $SUPERVISOR_PIDFILE not found, nothing to stop"
        fi

        exit $?

        ;;

    info)
        shift # Shift 'info' out of args so we can pass any
              # additional options to the real command
              # (right now only monasca-agent supports additional flags)
        su $AGENTUSER -c "$AGENTPATH info $@"
        COLLECTOR_RETURN=$?
        su $AGENTUSER -c "$MONASCASTATSDPATH info"
        MONASCASTATSD_RETURN=$?
        su $AGENTUSER -c "$FORWARDERPATH info"
        FORWARDER_RETURN=$?
        exit $(($COLLECTOR_RETURN+$MONASCASTATSD_RETURN+$FORWARDER_RETURN))
        ;;

    status)
        check_status
        ;;

    restart|force-reload)
        $0 stop
        $0 start
        ;;

    configcheck)
        su $AGENTUSER -c "$AGENTPATH configcheck"
        exit $?
        ;;

    configtest)
        su $AGENTUSER -c "$AGENTPATH configcheck"
        exit $?
        ;;

    jmx)
        shift
        su $AGENTUSER -c "$AGENTPATH jmx $@"
        exit $?
        ;;

    *)
        echo "Usage: /etc/init.d/$NAME {{start|stop|restart|info|status|configcheck|configtest|jmx}}"
        exit 1
        ;;
esac

exit $?
