#!/bin/ksh

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

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

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

#--- FUNC ------------------------------
do_shell_()
{
	local STREAMSERVER_PORT
	local STREAMSERVER_SECURE_PORT

	if [ -f "$ETC/virthost.sh" ]; then
		. "$ETC/virthost.sh"
	fi

	[ -z "$STREAMSERVER_PORT" ] && STREAMSERVER_PORT=8091
	[ -z "$STREAMSERVER_SECURE_PORT" ] && STREAMSERVER_SECURE_PORT=8093

	cat <<-EndOfInlineData
		DCVIEWER_HOME=$HOME/component/dcviewer
		DCVIEWER_VAR=$VAR/dcviewer
		STREAMSERVER_PORT=$STREAMSERVER_PORT
		STREAMSERVER_SECURE_PORT=$STREAMSERVER_SECURE_PORT
		STREAMSERVER_RUN=\$RUN/streamserver.run
		STREAMSERVER_PID=\$RUN/streamserver.pid

	EndOfInlineData

} #do_shell_()



check_streamserver_process_()
{
	local Pid="$1"
	local Cmd

	[ -z "${Pid}" ] && return 1
	Cmd=$( ps -p "${Pid}" -o comm h )
	[ "${Cmd}" = "streamserver" ] && return 0
	return 1
}

read_streamserver_pid_()
{
	cat "${STREAMSERVER_PID}" | grep '[0-9]\+'
}

check_streamserver_()
{
	if [ -f "${STREAMSERVER_PID}" ] ; then
		check_streamserver_process_ "$( read_streamserver_pid_ )"
		return $?
	fi

	return 1
}


ping_streamserver_() {
	# timeout applies to both connect, read and dns lookup (as we use IP to connect, the latter should not apply)
	wget -q -O - --no-http-keep-alive --timeout=3 --tries=3 "http://$SERVERIP:${STREAMSERVER_PORT}/" | awk 'BEGIN {res=1} /\<RUNNING\>/ {res=0; exit 0} END {exit res}'
	return $?
}


start_streamserver_()
{
	local WrapperPid

	if check_streamserver_ > /dev/null; then
		echo "--- Component dcviewer[$0 $$]: streamserver is running"
		return 0
	fi

	# first remove pid file if exists
	[ -f "${STREAMSERVER_PID}" ] && rm "${STREAMSERVER_PID}" 2>/dev/null

	touch "$RUN/streamserver.startup"
	[ -f "$LOG/streamserver.startup.log" ] && rm "$LOG/streamserver.startup.log"

	echo "Starting streamserver..."
	$DCVIEWER_HOME/wstreamserver.sh "${STREAMSERVER_PORT}" "${STREAMSERVER_SECURE_PORT}" 2>&1 | tee $LOG/streamserver.startup.log >>$LOG/streamserver.log 2>&1 &

	# save the pid of the wrapper started (well, it's the pid of tee)
	WrapperPid=$!

	#
	# Waiting for streamserver to start
	#

	counter=0
	while [ -n "$(ps -p $WrapperPid -o comm=)" ] ; do
		# The wrapper is still running

		# check if streamserver is up
		if ping_streamserver_ ; then
			# streamserver is up and listening
			# remove the startup flag and exit the loop
			rm "$RUN/streamserver.startup" 2>/dev/null

			return 0;
		fi

		let counter++;
		if [ "$counter" -ge 3 ] ; then
			echo "Connecting to streamserver at $SERVERIP failed" >&2
			stop_streamserver_
			break;
		fi

		echo "Retry connecting to streamserver"

		sleep 1
	done

	echo "Starting streamserver failed"
	exit 1
} #start_daemon()


start_herelod_()
{
	echo "Starting herelod..."
	# start herelod
	# number of channels (servers) can be configured in (var/)conf/herelod.cfg
	# as 
	# totalChannels="XX"
	# where XX is the desired number of channels, default value is 4
	[ -f ${HOME}/var/conf/herelod.cfg ] && NumOfServers=$(grep totalChannels ${HOME}/var/conf/herelod.cfg | tr -dc '0-9')
	[ -z "${NumOfServers}" ] && NumOfServers=$(grep totalChannels ${DCVIEWER_HOME}/conf/herelod.cfg | tr -dc '0-9')
	[ -z "${NumOfServers}" ] && NumOfServers=4
	$DCVIEWER_HOME/bin/herelod --servers ${NumOfServers} --syslog >>$LOG/herelod.log 2>&1 &
}



do_start_()
{
	local CWD=$( pwd )

	[ ! -d "$DCVIEWER_VAR" ] && mkdir $DCVIEWER_VAR 2>/dev/null
	
	[ -d "$HOME/htdocs/processed" ] && rm $HOME/htdocs/processed  # delete sim.link
	
	if [ -f "$DCVIEWER_HOME/invalidate_cache.flag" ] ; then
		# check if invalidate_cache.flag is not older then invalidate_cache.done
		# this will work correctly in case of invalidate_cache.done doesn't exist
		# (testing for newer wouldn't work in that case)
		if [ ! "$DCVIEWER_HOME/invalidate_cache.flag" -ot "$DCVIEWER_VAR/invalidate_cache.done" ] ; then
			if [ -n "$PROCESSED" -a -d "$PROCESSED" ] ; then
				mkdir $PROCESSED.new	 
				mkdir $HASHED_PROCESSED.new
				mv $PROCESSED $PROCESSED.old
				mv $PROCESSED.new $PROCESSED
				mv $HASHED_PROCESSED $HASHED_PROCESSED.old
				mv $HASHED_PROCESSED.new $HASHED_PROCESSED
				rm -fr $PROCESSED.old
				rm -fr $HASHED_PROCESSED.old
				/usr/bin/logger -p $LOG_FACILITY.info -t "dcviewer_ctrl[$$]" "start cleared processed files [$PROCESSED]"
			fi
			if [ -n "$CACHE" -a -d "$CACHE" ] ; then
				mkdir $CACHE.new	 
				mkdir $HASHED_CACHE.new
				mv $CACHE $CACHE.old
				mv $CACHE.new $CACHE
				mv $HASHED_CACHE $HASHED_CACHE.old
				mv $HASHED_CACHE.new $HASHED_CACHE
				rm -fr $CACHE.old
				rm -fr $HASHED_CACHE.old
				/usr/bin/logger -p $LOG_FACILITY.info -t "dcviewer_ctrl[$$]" "start cleared cache [$CACHE]"
			fi
			echo "Don't delete this file!!!!!" > $DCVIEWER_VAR/invalidate_cache.done
		fi
	fi

	if [ ! -z $1 ] ; then
		start_$1_
	else
		start_herelod_
		start_streamserver_
	fi
	cd $CWD

	return 0
} #do_start_()


stop_herelod_()
{
	# okosan leallit ha kell
	RES=$(check_supervisor_)
	
	if [ $RES -eq 1 ]; then
		pkill -f dcviewer/bin/herelod
		rm -f $HOME/var/run/herelod.pid
		rm -f $HOME/var/run/herelod.lock
	else
		$DCVIEWER_HOME/bin/herelocli --stop
	fi
}

stop_streamserver_()
{
	# Streamserver
	local Pid
	local ProcList

	rm "${STREAMSERVER_RUN}" >/dev/null 2>&1
	if [ -f "${STREAMSERVER_PID}" ] ; then
		Pid=$( read_streamserver_pid_ )
		if check_streamserver_process_ "${Pid}" ; then
			echo "killing streamserver (${Pid})"
			kill "${Pid}"
		else
			echo "streamserver process (${Pid}) does not exist"
		fi

		rm "${STREAMSERVER_PID}"
	fi

	ProcList=$( ps -C streamserver h -o pid )
	[ -z "${ProcList}" ] && return 0

	# streamserver processes are still running wait a millisec before start killall
	sleep 0.5
	ProcList=$( ps -C streamserver h -o pid )
	[ -z "${ProcList}" ] && return 0

	echo "streamserver process is still running (${ProcList}); killall" >&2
	killall streamserver
	sleep 0.01

	ProcList=$( ps -C streamserver h -o pid )
	[ -z "${ProcList}" ] && return 0

	echo "streamserver process is still running (${ProcList}); killall -9" >&2
	killall -9 streamserver

	ProcList=$( ps -C streamserver h -o pid )
	[ -z "${ProcList}" ] && return 0
	echo "streamserver process could not be stopped" >&2
	return 1
}

do_stop_()
{
	if [ ! -z $1 ] ; then
		stop_$1_
	else
		stop_herelod_
		stop_streamserver_
	fi
} #do_stop_()


status_streamserver_()
{
	if [ ! -f "$STREAMSERVER_RUN" ]; then
#		echo "ss STOPPED"
		return 2
	fi
	if [ ! -f "$STREAMSERVER_PID" ]; then
#		echo "ss ERROR"
		return 0
	fi

	if ! check_streamserver_; then
#		echo "ss ERROR"
		return 0
	fi

	# check if streamserver is up
	if ! ping_streamserver_ ; then
#		echo "ss ERROR"
		return 0
	fi

#	echo "ss OK"
	return 1
}

status_herelod_()
{
	RES=$(check_supervisor_)
	if [ $RES -eq 0 ]; then
		if $DCVIEWER_HOME/bin/herelocli --ping > /dev/null 2>&1; then
#			echo "hd OK"
			return 1
		else
#			echo "hd ERROR"
			return 0
		fi
	elif [ $RES -eq 2 ]; then
#		echo "hd STOPPED"
		return 2
	else
#		echo "hd ERROR"
		return 0
	fi
}

do_status_()
{
	local res=1
	if [ ! -z $1 ] ; then
		status_$1_
		res=$(($res * $?))
	else
		status_herelod_
		res=$(($res * $?))
		status_streamserver_
		res=$(($res * $?))
	fi

	if [ "$res" -eq "0" ] ; then
		echo "ERROR"
	elif [ "$res" -gt "1" ] ; then
		echo "STOPPED"
	else
		echo "OK"
	fi
} #do_status_()


do_beforesubmit_()
{
	do_stop_

} #do_beforesubmit_()

do_aftersubmit_()
{
	do_start_

} #do_aftersubmit_()

do_emergency_()
{
	do_stop_
	sleep 5
	do_start_
}

# 0 - should be running
# 1 - error - no supervisor
# 2 - stopped
check_supervisor_()
{
	# process pid - commandline
	
	if [ -f $HOME/var/run/herelod.pid ]; then
		SUPERVISOR_PID=$(cat $HOME/var/run/herelod.pid)
	
		if [ -d /proc/$SUPERVISOR_PID ]; then
			if grep -q herelod /proc/$SUPERVISOR_PID/cmdline; then
				echo 0
			else
				echo 1
			fi
		else
			echo 1
		fi
	else
		echo 2
	fi
}

#
# List files/tables to be backed up grouped by categories
#
# output lines should be in '<category> <type> <names>' format
#
do_listbackup_()
{
	cat <<-EOFLISTBACKUP
		config.system FILE ${CONF#$HOME/}/include.conf
	EOFLISTBACKUP
}

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

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

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

fi
