#!/bin/bash
#   Copyright 2017 Otavio Rodolfo Piske
#
#   Licensed under the Apache License, Version 2.0 (the "License");
#   you may not use this file except in compliance with the License.
#   You may obtain a copy of the License at
#
#       http://www.apache.org/licenses/LICENSE-2.0
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.

localdir=`dirname $0`
installdir=`dirname $localdir`

if [ "$installdir" = "." ] ; then
	installdir=".."
fi

source "$installdir"/config/maestro-exporter-service.conf

function start() {
    nohup "$installdir"/bin/maestro-exporter -m "$MAESTRO_BROKER" $@ > /dev/null 2> /dev/null &
    sleep 2s
    for pid in $(ps -ef | grep -i maestro-exporter | grep java | grep -v bash | grep -v exporter-service | grep -v grep | awk ' { print $2 } ') ; do
        echo "Maestro exporter started $pid"
    done
}

function stop() {
    for pid in $(ps -ef | grep maestro-exporter | grep java | grep -v bash | grep -v exporter-service | grep -v grep | awk ' { print $2 } ') ; do
        echo "Killing maestro-exporter $pid"
        kill -TERM $pid
    done
}

function restart() {
    stop
    start

}

function help() {
    echo "Usage: $0 [start|stop|restart]"
}


if [[ -z "$1" ]] ; then
    help
    exit 1
fi


case "$1" in
	start)
		start $2 $3
		;;
	stop)
		stop
		;;
	restart)
		restart
		;;
	*)
		help
		RETVAL=2
esac