#!/bin/bash -
export PORT=8686
HOME_DIR='/opt/vprotect/tapemanager'

error () {
if [ "$1" = 0 ]
 then
  echo "ok"
 else
  if [ "$2" = 0 ]
   then
    echo -e "$1 [${YELLOW}WARNING${NC}]"
   else
    echo -e "$1 [${RED}ERROR${NC}]"
    echo The configuration process was interrupted.
    exit
   fi
fi
}

trap "exit;" SIGHUP SIGINT SIGTERM

get_pid()
{
	PID=`netstat -tlnp |& grep "$PORT" | awk '{print $7}' | sed -E "s#([0-9]+)/java#\1#"`
}

service_status()
{
	get_pid
	if [ -z "$PID" ]
	then
		echo "SBR Tape Manager is not running."
		running=false
	else
		echo "SBR Tape Manager  is running (PID = $PID)."
		running=true
	fi
}

cd $HOME_DIR || exit

case "$1" in
	"status")
		service_status
		;;

	"start")
		echo "Starting SBR Tape Manager ..."
		nohup java -jar $HOME_DIR/sbr-tape-manager.jar >/dev/null 2>&1 &
		sleep 3

		service_status

		if [ "x$running" == "xfalse" ]
		then
			echo "Please check log files: $HOME_DIR/logs/tapemanager/tape_manager.log*"
		fi
		;;

	"stop")
		get_pid

		if [ ! -z "$PID" ]
		then
			echo "Stopping SBR Tape Manger (PID = $PID)..."
			kill "$PID"
			sleep 1
		fi

		service_status
		;;
	*)

esac
