#! /bin/bash
#=======================================================================
# NOTE: This one needs more work...
#-----------------------------------------------------------------------
scriptPath="$( cd -P "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

baseDir=/opt/sek_ase_auditor
configFile=${baseDir}/sek_ase_auditor.properties
consoleLogFile=${baseDir}/0/log/sek_ase_auditor.console

javaClassName="sek.ase.auditor.AseAuditor"

##
## Check if it's already running
##
echo " * Checking if 'sek_ase_auditor' is already running"
echo ""
pidCount=$(ps -ef | grep "${javaClassName}" | grep -v grep | wc -l)
pid=$(ps -ef | grep "${javaClassName}" | grep -v grep | awk '{printf "%s ", $2}')

if [ ${pidCount} -gt 0 ]
then
	echo " * Found ${pidCount} 'sek_ase_auditor' processes... with PID=${pid}"
	echo " * I will NOT start a new one."
	echo " * To stop the previously running process, do:"
	echo "   exec: ./stop_auditor.sh "
	echo "     or: kill ${pid}"
	echo ""
	exit 1
fi

##
## Start the auditor
##
echo " * Starting 'sek_ase_auditor'"
echo ""
nohup ${baseDir}/0/bin/sek_ase_auditor.sh -C ${configFile} > ${consoleLogFile} 2>&1 &

echo " * Sleeping for 3 seconds, then test if 'sek_ase_auditor' is running..."
sleep 3
pidCount=$(ps -ef | grep "${javaClassName}" | grep -v grep | wc -l)
pid=$(ps -ef | grep "${javaClassName}" | grep -v grep | awk '{printf "%s ", $2}')

if [ ${pidCount} -eq 0 ]
then
	echo ""
	echo "===================================================================="
	cat ${consoleLogFile}
	echo "===================================================================="
	echo " * FAILED to start 'sek_ase_audit'"
	echo " * Above is the latest console log file: ${consoleLogFile}"
	echo ""
	
	exit 1
else
	echo ""
	echo " * Found ${pidCount} 'sek_ase_auditor' processes... with PID=${pid}"
	echo ""

	exit 0
fi
