#!/bin/bash

NAME='onapp_mq_tracer'
SCRIPT=/onapp/utilities/mq-tracer/onapp_mq_tracer
LOGFILE=/onapp/utilities/mq-tracer/trace.log
CONFIG_FILE=/onapp/utilities/mq-tracer/config.yml

remove_logfile(){
    test -f $LOGFILE
    if [ $? -eq 0 ]; then
        rm $LOGFILE
    fi
}

mq_host(){
    grep rabbitmq_host $CONFIG_FILE 2>/dev/null | cut -d' ' -f2
}

set_trace(){
    if ! mq_host &>/dev/null; then
        echo "Failed configuration"
        exit 1
    fi

    ip a | grep $(mq_host)

    if [ $? -eq 0 ]; then
        if [ "$1" = "on" ]; then
            rabbitmqctl trace_on
        elif [ "$1" = "off" ]; then
            rabbitmqctl trace_off
        else
            echo "Unprocessable action $1"
            exit 1
        fi
    else
        if [ "$1" = "on" ]; then
            ssh root@$(mq_host) -t 'rabbitmqctl trace_on'
        elif [ "$1" = "off" ]; then
            ssh root@$(mq_host) -t 'rabbitmqctl trace_off'
        else
            echo "Unprocessable action $1"
            exit 1
        fi
    fi
}


start_process(){
    remove_logfile
    set_trace on
    nohup $SCRIPT 2&>/dev/null &
}

start(){
    check_service $NAME
    if [ $? -eq 0 ]; then
        echo "$NAME is already running"
        exit 1
    else
        echo "Starting $NAME"
        start_process
        sleep 1
        exit 0
    fi
}

stop_process(){
    pkill -15 -f $NAME
    set_trace off
}

stop(){
    check_service $NAME
    if [ $? -eq 0 ]; then
        echo "Stopping $NAME"
        stop_process
        exit 0
    else
        echo "$NAME is already stopped"
        exit 1
    fi
}

restart(){
    check_service $NAME
    if [ $? -eq 0 ]; then
        echo "Stopping $NAME"
        stop_process
        echo "Starting $NAME"
        start_process
    else
        echo "$NAME is already stopped"
        echo "Starting $NAME"
        start_process
    fi
    exit 0
}

status(){
    check_service $NAME
    if [ $? -eq 0 ]; then
        echo -e "${NAME} is running"
        exit 0
    else
        echo -e "${NAME} is stopped"
        exit 1
    fi
}

usage(){
    $SCRIPT usage
}

log(){
    tail -f $LOGFILE
}

check_service(){
    pids=`ps ax | grep $1 | grep -v $0 | grep -v grep` > /dev/null
    if [ "x$pids" = "x" ]; then
        return 1
    else
        return 0
    fi
}

case "$1" in
  status)
        status
        ;;
  start)
        start
        ;;
  log)
        log
        ;;
  stop)
        stop
        ;;
  restart)
        restart
        ;;
  *)
        usage
        ;;
esac
