#!/bin/bash
#
# /etc/init.d/newrelic_mysql_agent -- Startup/shutdown script for New Relic MySQL Plugin
#
# Written by Mustafa Ashurex <mustafa@ashurexconsulting.com>.
#
#
### BEGIN INIT INFO
# Provides: newrelic_mysql_plugin
# Required-Start: $Local_fs $remote_fs $network $sysLog
# Required-Stop: $Local_fs $remote_fs $network $sysLog
# Should-Start: $named
# Should-Stop $named
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Description: Start and stop the New Relic MySQL Plugin
# Short-Description: Start and stop New Relic MySQL Plugin
### END INIT INFO

## Source function Library
. /etc/rc.d/init.d/functions

NR_MYSQL_PLUGIN_PID="/var/run/newrelic_mysql_plugin.pid"
NR_MYSQL_PLUGIN_VERSION="1.0.4"

export NR_MYSQL_PLUGIN_PID
export NR_MYSQL_PLUGIN_VERSION

if [[ -z "$NR_MYSQL_PLUGIN_HOME" ]]
then
         NR_MYSQL_PLUGIN_HOME="/etc/newrelic/newrelic_mysql_plugin-$NR_MYSQL_PLUGIN_VERSION"
         export NR_MYSQL_PLUGIN_HOME
fi

if [[ -z "$NR_MYSQL_PLUGIN_HOME" ]]
then
    echo NR_MYSQL_PLUGIN_HOME must be set!
    exit 5
fi

plugin_pid() {
    # This gets the pid from ps
    echo `ps aux | grep newrelic_mysql_plugin | grep -v grep | awk '{ print $2  }'`
}

plugin_start() {
    pid=$(plugin_pid)
    if [ -n "$pid" ]; then
        echo "Plugin is already running (pid: $pid)."
    else
        cd $NR_MYSQL_PLUGIN_HOME
        echo "Starting Plugin..."
        echo -n $pid > $NR_MYSQL_PLUGIN_PID
        `java -jar $NR_MYSQL_PLUGIN_HOME/newrelic_mysql_plugin-$NR_MYSQL_PLUGIN_VERSION.jar` > /dev/null 2>&1 &
        echo "Plugin started."
    fi
    return 0
}

plugin_stop() {
    pid=$(plugin_pid)
    if [ -n "$pid" ]
    then
        echo "Stopping Plugin..."
        kill -9 $pid
        rm $NR_MYSQL_PLUGIN_PID
        echo "Plugin stopped."
    else
        echo "Plugin is not running."
    fi
    return 0
}

plugin_status() {
    pid=$(plugin_pid)
    if [ -n "$pid" ]
    then
        echo "Plugin is running with pid: $pid."
    else
        echo "Plugin is not running."
    fi
    return 0
}

case $1 in
start)
    plugin_start
    ;;
stop)
    plugin_stop
    ;;
restart)
    plugin_stop
    plugin_start
    ;;
status)
    plugin_status
    ;;
*)
    echo "Missing required directive [start | stop | status]"
    exit 1
    ;;
esac
exit 0