#!/bin/ksh
#
# Component: etc
#
# Description:
#  Control script for medsrv
#
# the normal start now inlcudes config, too
# the 'start noconfig' means start without config

#--- INIT ------------------------------
origCommand=$@
RCLOG=$HOME/var/log/rc.log

function log_to_file {
       if [ -z "$1" ]; then
           echo  >> $RCLOG
       else
           echo "$(date "+%Y-%m-%d %H:%M:%S") $@" >> $RCLOG
       fi
}


if [ "config" == "$1" ] || { [ "start" == "$1" ] && [ "noconfig" != "$2" ]; } then
	if [ -f "$HOME/etc/setenv.sh" ]; then
		if ! grep -q RUNNING_RC_CONFIG_DONT_INCLUDE "$HOME/etc/setenv.sh" ; then
			# remove legacy setenv.sh
			rm -f $HOME/etc/setenv.sh
		fi
	
		# set the don't include flag to avoid setenv.sh being processed by control scripts
		RUNNING_RC_CONFIG_DONT_INCLUDE="true"
		export RUNNING_RC_CONFIG_DONT_INCLUDE
	fi
fi

[ ! -e $HOME/tmp/ ] && mkdir -p $HOME/tmp/

$HOME/etc/ctrl shell >$HOME/tmp/setenv.1.$$
sed 's/\(.*\)=.*/export \1/g' $HOME/tmp/setenv.1.$$ > $HOME/tmp/setenv.2.$$
cat $HOME/tmp/setenv.1.$$ $HOME/tmp/setenv.2.$$ > $HOME/tmp/setenv.3.$$

. $HOME/tmp/setenv.3.$$
[ 0 = $? ] && rm $HOME/tmp/setenv.?.$$

. /etc/erad-base/setenv.sh
. $HOME/etc/func.shi

FileColor=${ColorLightBlue}

SELF=`basename $0`

COMMANDS="start stop status setup shell crontab monitor capture listbackup"
RCCOMMANDS="$COMMANDS config"

set -A ErrorStrings 'error' 'exception' 'severe' 'not\\ found' 'cannot' 'no\\ such'


AllCtrl="$HOME/etc/ctrl"
BackCtrl="$HOME/etc/ctrl"
for Compo in ${COMPONENTS_S}; do
	Ctrl=$HOME/component/${Compo}/ctrl
	if [ -x "$Ctrl" ]; then
		AllCompo="$AllCompo $Compo"
		AllCtrl="$AllCtrl $Ctrl"
		BackCtrl="$Ctrl $BackCtrl"
	fi
done

#--- FUNC ------------------------------
check_action_()                         #check action argument (start stop ...)
{
	for c in $RCCOMMANDS; do
		[ "$c" = "$1" ] && return 0
	done

	usage_
	return 1

} #check_action_()

#---------------------------------------
usage_()
{
	# regopsys color
	local reg="${ColorCyan}"
	# option color
	local opt="${ColorYellow}"
	# option argument color
	local arg="${ColorLightMagenta}"
	# reset color
	local end="${FontReset}"

	echo -e "${reg}Usage: [${opt}component${end}=${arg}{component}${end}] $SELF {${arg}command${end}}"
	echo -e "	implemented commands:"
	echo -e	"	${arg}$RCCOMMANDS${end}"


} #usage_()

function print_formatted {
	while read -r line; do
		Color=${VerboseColor}
		for errorStr in ${ErrorStrings[@]}; do
			if echo $line | egrep -iq $errorStr; then
				Color=${ErrorColor}
				break;
			fi
		done
		echo -e "${Color}$line${FontReset}"
		log_to_file $line
	done <<< "$1"
}

function run_formatted {
	log_to_file "++Command executed: $@"
	
	Output=$( $@ 2>&1 )
	RES=$?
	
	# check if there is a redirection
#	if $(echo $Output | egrep -q "^#SUBCTRLLIST"); then
	if [[ "$Output" == \#SUBCTRLLIST* ]]; then
		while read -r subctrl; do
            [[ "$subctrl" == "" || "$subctrl" == \#* ]] && continue
			echo -ne "\\r# ${InfoColor}Running ${FileColor}$subctrl${InfoColor} ${ColorLightMagenta}$action${FontReset}                                     "      
			log_to_file "Running $subctrl $action"
			run_formatted "$subctrl $action"
			RES=$?
			
			if [ "${action}" == "start" ] &&  [ "$HOME/component/web/cases/ctrl" == ${subctrl} ] && [ $RES -ne 0 ] ; then
					# I don't make it general, only for web/cases, to be on the safe side
					echo -ne "${ErrorColor}Terminating the web/ctrl start process!${FontReset}"
					echo
					log_to_file "Terminating the web/ctrl start process!"
					return $RES	
			fi
			
		done <<< "$Output"
	else
		if [ -n "$Output" ]; then
			echo
            if [ "$action" == "capture" ]; then
                echo -e "$Output"
            else
			    print_formatted "$Output"
            fi
            log_to_file
			echo
		fi
	fi
	return $RES
}

function run_ {
	Output=$( $@ 2>&1 )
	# check if there is a redirection
#	if $(echo $Output | egrep -q "^#SUBCTRLLIST"); then
	if [[ "$Output" == \#SUBCTRLLIST* ]]; then
		while read -r subctrl; do
                        [[ "$subctrl" == "" || "$subctrl" == \#* ]] && continue
			echo -ne "\\r# Running $subctrl $action"
			log_to_file "# Running $subctrl $action"
			run_ "$subctrl $action"
		done <<< "$Output"
	else
		if [ -n "$Output" ]; then
			echo
			echo "$Output"
			echo
			log_to_file "$Output"
		fi
	fi
}

function print_crontab {
	for Ctrl in $AllCtrl; do
		echo "# --- $Ctrl crontab ---"
		$Ctrl crontab
		echo
	done
}

#---------------------------------------
function make_crontab {
# --- config creates crontab file then, the 'crontab' commands
	print_crontab | crontab -
} #make_crontab()


# Remove dangling link from component, htdocs
function clear_dangling_links {
	if command -v symlinks >/dev/null 2>&1 ; then
		symlinks -d "${HOME}/component/" >/dev/null 2>&1
		symlinks -d "${HOME}/htdocs/" >/dev/null 2>&1
	fi
}

#--- MAIN ------------------------------
echo
check_action_ $1
	[ 0 != $? ] && exit 1

action=$1

param2=$2

log_to_file "===============\n"
log_to_file "etc/rc $origCommand started"

# remove 'noconfig' from $@ - not to send it to subctrl-s
for arg do
  shift
  [ "$arg" = "noconfig" ] && continue
  set -- "$@" "$arg"
done

# --- config is a special command ---
# start without the 'noconfig' parameter incorporates config now
if [ "config" == "$1" ] || { [ "start" == "$1" ] && [ "noconfig" != "$param2" ]; } then
	echo -e "# ${InfoColor}Building ${ColorLightMagenta}$HOME/etc/setenv.sh${FontReset} from: ${ColorLightBlue}$AllCompo${FontReset}\\n"

	# first check and create VAR/CONF
	[ ! -d "$VAR" ] && mkdir $VAR
	[ ! -d "$CONF" ] && mkdir $CONF

	CWD=`pwd`
	cd $ETC

	[ -f "$ETC/virthost.sh" -a ! -L "$ETC/virthost.sh" ] && mv $ETC/virthost.sh $CONF/

	if [ -f "$CONF/virthost.sh" ] ; then
		[ ! -L "virthost.sh" ] && ln -s $CONF/virthost.sh
	else
		[ -L "virthost.sh" ] && rm -f virthost.sh
	fi

        # running setup phase for the components that need linking, moving files, etc
        $HOME/etc/rc setup

	echo "if [ \"true\" != \"\$RUNNING_RC_CONFIG_DONT_INCLUDE\" ] ; then" >$CONF/setenv.sh.$$
	for Ctrl in $AllCtrl; do
		echo "# --- $Ctrl ---"

# --- config creates setenv. files first, using each 'shell' commands
		Assign=`$Ctrl shell`
		Err=$?

		if [ 0 = $Err ]; then
			if [ -n "$Assign" ] ; then
				cat <<-EOI
					$Assign
				EOI
				echo
				echo export `( cat <<-EOI
					$Assign
				EOI
				) | grep -v ^# | sed -e 's|=.*||'`
			fi
		else
			echo "# $Assign"

		fi
		echo

	done >>$CONF/setenv.sh.$$
	echo "fi" >>$CONF/setenv.sh.$$
	mv $CONF/setenv.sh.$$ $CONF/setenv.sh

	# Clear the don't include flag for the setenv.sh has been re-generated
	RUNNING_RC_CONFIG_DONT_INCLUDE="false"
	export RUNNING_RC_CONFIG_DONT_INCLUDE

	. $CONF/setenv.sh

	for Var in `sed -n "/^export/ s|^export ||p" $CONF/setenv.sh`; do
		eval Val=\$$Var
		echo env${Var}=\"$Val\"
	done >$CONF/setenv.rec.$$
	mv -f $CONF/setenv.rec.$$ $CONF/setenv.rec

	sort -u $CONF/setenv.rec | sed -e 's/^env//' -e 's/"//g'>> $CONF/setenv.prp.$$
	mv -f $CONF/setenv.prp.$$ $CONF/setenv.prp

	# Remove generated config files in ~/etc/
	for cfgfile in setenv.sh setenv.rec setenv.prp setenv.p3i; do [ -f "$ETC/$cfgfile" -a ! -L "$ETC/$cfgfile" ] && rm -f $ETC/$cfgfile; done

	# Link generated config files in ~/etc/ to ~/var/conf
	for cfgfile in setenv.sh setenv.rec setenv.prp; do [ ! -L "$cfgfile" ] && ln -s $CONF/$cfgfile $ETC/$cfgfile; done

	# Process crontabSchedule.cfg and create crontabSchedule.shi for crontab entries
	[ -x "$ETC/genCrontabScheduleShi.sh" ] && $ETC/genCrontabScheduleShi.sh

	cd $CWD

# if we have 'start', meaning 'config + start', we go on to apply 'start'
# otherwise 'config' ends here
	if [ "config" == "$1" ] ; then
		exit 0;	
	fi

fi


# --- config is a special command, but the other commands are performed here

versiontolog=`rpm -qa|grep medsrv8.0-server`
if [ $? -ne 0 ]; then
	versiontolog="NA(dev_server)"
fi  

echo -e "# ${InfoColor}Sending ${ColorLightMagenta}$1${FontReset} to: ${ColorLightBlue}$AllCompo${FontReset}\\n"
log_to_file "# Sending $1 to: $AllCompo\n"

CtrlList="$AllCtrl"
# we need a reserve order for stop
if [ "$1" == "start" ]; then
	if [ -f "$service_subsys_lockdir/$MED_USER" ]; then
		echo "${ErrorColor}MEDSRV is already running, or stale subsys lockfile ${FileColor}$service_subsys_lockdir/$MED_USER${ErrorColor} exist!${FontReset}" >&2
		echo "Check and clean up lockfile as root!" >&2
		log_to_file "MEDSRV is already running, or stale subsys lockfile $service_subsys_lockdir/$MED_USER exist!"
		log_to_file "Check and clean up lockfile as root!" 
		exit 1
	fi

	echo -ne "\\r# ${InfoColor}Running ${FileColor}$ASROOT localconf.asr ${ColorLightMagenta}pre-medsrv-start${FontReset}"
	log_to_file "# Running $ASROOT localconf.asr pre-medsrv-start"
	run_formatted $ASROOT localconf.asr pre-medsrv-start
elif [ "$1" == "stop" ]; then
	if [ ! -f "$service_subsys_lockdir/$MED_USER" ]; then
		echo "${ErrorColor}MEDSRV is not running, or missing subsys lockfile ${FileColor}$service_subsys_lockdir/$MED_USER${ErrorColor}! " >&2
		echo "${InfoColor}If MEDSRV was running, it does not need to be restarted after a system shutdown/reboot.${FontReset}" >&2
		echo "Touch the file as root, then try again! " >&2
		log_to_file "MEDSRV is not running, or missing subsys lockfile $service_subsys_lockdir/$MED_USER! If MEDSRV was running, it does not need to be restarted after a system shutdown/reboot. Touch the file as root, then try again!"
		exit 1
	fi

	echo -ne "\\r# ${InfoColor}logging stop into database and file${FontReset}                                   "
	log_to_file "# logging stop into database"
	run_formatted $LOG_HOME/logintodatabase.sh -p "INFO" -l "OTHER" -a "stop" -u "system" -m "medsrv_stopped,version:$versiontolog"
	/usr/bin/logger -p $LOG_OPER_FACILITY.info -t "rcstop[$$]" "INFO OTHER stop system - - - - - - - - - - - medsrv_stopped,version:$versiontolog"

	echo -ne "\\r# ${InfoColor}Running ${FileColor}$ASROOT localconf.asr ${ColorLightMagenta}pre-medsrv-stop${FontReset}                              "
	log_to_file "# Running $ASROOT localconf.asr pre-medsrv-stop"
	run_formatted $ASROOT localconf.asr pre-medsrv-stop

	CtrlList="$BackCtrl"
	crontab -r
    elif [ "$1" == "crontab"  ]; then
            print_crontab
            exit 0
fi

echo

for Ctrl in ${CtrlList}; do
            if [[ "$1" == "capture" || "$1" == "monitor" ]]; then
	    		echo -ne "\\r# Running $Ctrl $1                                     "
	    		run_ $Ctrl "$@"
	        else
	    		echo -ne "\\r# ${InfoColor}Running ${FileColor}$Ctrl${InfoColor} ${ColorLightMagenta}$1${FontReset}                                     "         
	    		log_to_file "# Running $Ctrl $1"                           
	    		run_formatted $Ctrl "$@"
	    		RES=$?
	    		
				if [ "$1" == "start" ] && [ "$HOME/component/web/ctrl" == ${Ctrl} ] && [ $RES -ne 0 ] ; then
					# I can't make it general, only for web/cases, because different ctrl processes give different nonzero results for some reason...
					echo -ne "${ErrorColor}Terminating the whole startup process!${FontReset}"
					echo
					log_to_file "Terminating the whole startup process!"
					# we still run this because we cannot stop medsrv afterwards if we don't
					run_formatted $ASROOT localconf.asr post-medsrv-start
					
					exit $RES	
				fi	
    		            
            fi
done

if [ "$1" == "start" ]; then
	# create crontab entries
	make_crontab
	# remove danglink links from component, htdocs
	clear_dangling_links
	echo -ne "\\r# ${InfoColor}Running ${FileColor}$ASROOT localconf.asr ${ColorLightMagenta}post-medsrv-start${FontReset}                          "                    
	log_to_file "# Running $ASROOT localconf.asr post-medsrv-start" 
	run_formatted $ASROOT localconf.asr post-medsrv-start

	echo -e "\\r# ${InfoColor}logging start into database and file${FontReset}                                                  "
	log_to_file "# logging start into database"
	run_formatted $LOG_HOME/logintodatabase.sh -p "INFO" -l "OTHER" -a "start" -u "system" -m "medsrv_started,version:$versiontolog"
	/usr/bin/logger -p $LOG_OPER_FACILITY.info -t "rcstart[$$]" "INFO OTHER start system - - - - - - - - - - - medsrv_started,version:$versiontolog"
	
elif [ "$1" == "stop" ]; then
	echo -e "\\r# ${InfoColor}Running ${FileColor}$ASROOT localconf.asr ${ColorLightMagenta}post-medsrv-stop${FontReset}                       "          
	log_to_file "# Running $ASROOT localconf.asr post-medsrv-stop"          
	run_formatted $ASROOT localconf.asr post-medsrv-stop
fi

log_to_file "etc/rc $origCommand finished"
echo
