#!/bin/ksh

# Component: services
#
# Description:
#  Control script of component services
#

#--- INIT ------------------------------
#needs $HOME
. $HOME/etc/ctrl.main.shi

[ -f $HOME/etc/setenv.sh ] && . $HOME/etc/setenv.sh

[ -f $RMIREGISTRY_PID ] && PID=`cat "$RMIREGISTRY_PID" 2>&1`
[ "" = "$PID" ] && PID="$$.not"

#--- FUNC ------------------------------
do_shell_()
{
	[ -z "$RMIREGISTRY_PORT" ] && RMIREGISTRY_PORT=1099

	cat <<-EndOfInlineData
		SERVICES_HOME=$HOME/component/services
		RMIREGISTRY_PORT=$RMIREGISTRY_PORT
		RMIREGISTRY_PID=\$RUN/rmiregistry.pid
		OBSERVER_CRASH_HOME=$HOME/crashlog

	EndOfInlineData

} #do_shell_()

do_start_()
{
	if [ -n "$1" ]; then
		LOCAL_VM=`$JAVA_HOME/bin/java -cp $CLASSPATH:$HOME/component/services/query.jar com.erad.pacs.modules.ModuleQuery`
		Found=""
		for VM in $LOCAL_VM
		do
			if [ "$VM" == "$1" ]; then
				Found="true"
				StillRunning=""
				if [ -e $RUN/$VM.service.pid ]; then
					PID=$( cat $RUN/$VM.service.pid )
					[ -n "$( ps cax|grep $PID )" ] && StillRunning="true"
				fi
				
				JVM_OPTIONS=""
				if [ -e $RUN/$VM.service.options ]; then
					JVM_OPTIONS=$( cat $RUN/$VM.service.options )
				fi
				
				if [ -z "$StillRunning" ]; then
					$JAVA_HOME/bin/java -cp $CLASSPATH -Djava.locale.providers=COMPAT,CLDR -Dpacs.self.machine=local -Dpacs.self.host=$VM $JVM_OPTIONS -XX:+CreateCoredumpOnCrash com.erad.pacs.services.$VM.service.Standalone >>$HOME/var/log/$VM.service.log 2>&1 &
#					$JAVA_HOME/bin/java -Xrunjdwp:transport=dt_socket,address=8600,server=y,suspend=n -cp $CLASSPATH -Dpacs.self.machine=local -Dpacs.self.host=$VM $JVM_OPTIONS com.erad.pacs.services.$VM.service.Standalone   >$HOME/var/log/$VM.service.log 2>&1 &
					echo $! > $RUN/$VM.service.pid
				else
				    echo "--- Component services[$0 $$]: $1 is still running ($PID)"
				fi
			fi
		done		
		if [ -z "$Found" ]; then
			echo "--- Component services[$0 $$]: No standalone configured module found with the name '$1'"
			exit 1
		fi
	else
		if [ ! -e "/proc/$PID" ]; then
			
			if [ -n "$(ps -C java h | grep rmiregistry | grep $JAVA_HOME)" ] ; then
				echo " WARNING: rmiregistry is already running" >&2
				echo ps h | grep rmiregistry | grep $JAVA_HOME
				exit 1
			fi
		
			CLASSPATH="$CLASSPATH:$HOME/component"
			export CLASSPATH
			
			$JAVA_HOME/bin/rmiregistry $RMIREGISTRY_PORT -J--add-modules=java.sql >$HOME/var/log/rmiregistry.log 2>&1 &
			echo $! >$RMIREGISTRY_PID
			
			$JAVA_HOME/bin/java -cp $CLASSPATH:$HOME/component/services/query.jar com.erad.pacs.rmi.WaitForRmiRegistry
			if [ $? -eq 1 ]; then
				exit 1
			fi
	
			LOCAL_VM=`$JAVA_HOME/bin/java -cp $CLASSPATH:$HOME/component/services/query.jar com.erad.pacs.modules.ModuleQuery`
			for VM in $LOCAL_VM
			do
				JVM_OPTIONS=""
				if [ -e $RUN/$VM.service.options ]; then
					JVM_OPTIONS=$( cat $RUN/$VM.service.options )
				fi
			
				$JAVA_HOME/bin/java -cp $CLASSPATH -Djava.locale.providers=COMPAT,CLDR -Dpacs.self.machine=local -Dpacs.self.host=$VM $JVM_OPTIONS -XX:+CreateCoredumpOnCrash com.erad.pacs.services.$VM.service.Standalone  >>$HOME/var/log/$VM.service.log 2>&1 &
	#			$JAVA_HOME/bin/java -Xrunjdwp:transport=dt_socket,address=8600,server=y,suspend=n -cp $CLASSPATH -Djava.locale.providers=COMPAT,CLDR -Dpacs.self.machine=local -Dpacs.self.host=$VM $JVM_OPTIONS com.erad.pacs.services.$VM.service.Standalone   >$HOME/var/log/$VM.service.log 2>&1 &
				echo $! > $RUN/$VM.service.pid
			done		
	
			cd $CWD
		else
			echo "--- Component services[$0 $$]: rmiregistry is running"
		fi
	fi

} #do_start_()


#
# $1 might be soft:
#
do_stop_()
{
	if [ -n "$1" ]; then
		LOCAL_VM=`$JAVA_HOME/bin/java -cp $CLASSPATH:$HOME/component/services/query.jar com.erad.pacs.modules.ModuleQuery`
		Found=""
		for VM in $LOCAL_VM
		do
			if [ "$VM" == "$1" ]; then
				Found="true"
				if [ -e $RUN/$VM.service.pid ]; then
					PID=$( cat $RUN/$VM.service.pid )
					kill $PID
					rm $RUN/$VM.service.pid
				fi
			fi
		done
		if [ -z "$Found" ]; then
			echo "--- Component services[$0 $$]: No standalone configured module found with the name '$1'"
			exit 1
		fi
	else
		LOCAL_VM=`$JAVA_HOME/bin/java -cp $CLASSPATH:$HOME/component/services/query.jar com.erad.pacs.modules.ModuleQuery`
		for VM in $LOCAL_VM
		do
			if [ -f $RUN/$VM.service.pid ]; then
				kill `cat $RUN/$VM.service.pid`
				rm $RUN/$VM.service.pid
				
			fi
		done
	
		#killing Java rmi registry			
		rmiregistryPID=`ps wwwU $USER | grep "[r]miregistry $RMIREGISTRY_PORT" | awk '{print $1}'`
		if [ -n "$rmiregistryPID" ] ; then
			kill $rmiregistryPID
		fi
		
		rm $RMIREGISTRY_PID
	fi
} #do_stop_()

do_status_()
{
	if [ -n "$1" ]; then
		LOCAL_VM=`$JAVA_HOME/bin/java -cp $CLASSPATH:$HOME/component/services/query.jar com.erad.pacs.modules.ModuleQuery`
		Found=""
		for VM in $LOCAL_VM
		do
			if [ "$VM" == "$1" ]; then
				Found="true"
				if [ -e $RUN/$VM.service.pid ]; then
					PID=$( cat $RUN/$VM.service.pid )
					[ -n "$( ps cax|grep $PID )" ] && echo "RUNNING" || echo "STOPPED"
					exit
				else
				    echo "STOPPED"
				    exit
				fi
			fi
		done
		if [ -z "$Found" ]; then
			echo "--- Component services[$0 $$]: No standalone configured module found with the name '$1'"
			exit 1
		fi
	else
		if [ ! -f $RMIREGISTRY_PID ]; then
			echo "STOPPED"
			exit
		fi
  
		if [ -z "$(ps -C rmiregistry h | grep "\<${RMIREGISTRY_PORT}\>")" ] ; then
			echo "ERROR"
			exit
		fi
	fi

	echo "OK"

} #do_status_()

do_beforesubmit_()
{
  do_stop_

} #do_beforesubmit_()

do_aftersubmit_()
{ 
  do_start_

} #do_aftersubmit_()

do_emergency_()
{
  do_stop_
  sleep 10
  do_start_

} #do_emergency_()

do_capture_() 
{
	for pidFile in $(find ${HOME}/var/run/ -name *.service.pid); do
		servicePid=$(cat $pidFile)
		# if it would be bash..
		# [[ "$pidFile" =~ (.+)\.service\.pid$ ]]
		# serviceName=${BASH_REMATCH[1]}
		serviceName=$(basename $pidFile|cut -d. -f1)
		
		echo "Threads for ${serviceName} service:"
		echo 
		if [ -n "$servicePid" ] ; then
			timeout_ 10 $JAVA_HOME/bin/jstack $servicePid 2>/dev/null 
			if [ $? -ne 0 ] ; then
				timeout_ 10 $JAVA_HOME/bin/jstack -F $servicePid 2>/dev/null
				if [ $? -ne 0 ] ; then
					echo "Capturing ${serviceName} service threads failed"
				fi
			fi
		else 
			echo "No ${serviceName} service PID found, but pid file exists?!" 
		fi
	done 
}


do_monitor_()
{
    HERMES_PID_FILE="${RUN}/hermes.service.pid"
    [ -f $HERMES_PID_FILE ] && PID=`cat "$HERMES_PID_FILE" 2>&1`
    #echo "hermes PID=$PID"
    #THREADCOUNT=$(ps -ho thcount -p $PID | awk '{$1=$1};1')
    # CentOS 7 compatible solution:
    THREADCOUNT=$(ps huH p ${PID} | wc -l)
    echo "hermes_thread_num=$THREADCOUNT"
}


#
# Executes a command and kills after a given timeout
#
# $1 - timeout seconds
# $@ - command and arguments to execute
#
timeout_() {
	local to
	local pid
	local waiter
	local exitcode

	to=$1
	shift

	# start the command in background
	( $@ 2>&1 ) & pid=$!


	# start a background process to kill command after timeout expired
	(sleep $to && kill_ $pid) & waiter=$!


	# wait for the command to complete
	wait $pid

	# exit code of the process - indicates whether it was killed or not
	exitcode=$?

	# kill the 'timeout killer' process if still runs
	kill_ $waiter

	return $exitcode
}

#--- MAIN ------------------------------

check_action_ $1
if [ 0 = $? ]; then
  do_$1_ $2

else
  echo "--- Component services [ctrl $$]: Bad command: $1" >&2
  exit 1

fi
