#!/bin/ksh
#
# Component: iface
#
# Description:
#  Control script of component iface
#

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

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

#--- FUNC ------------------------------
do_shell_()
{
	cat <<-EndOfInlineData
		IFACE_HOME=$HOME/component/iface
		IFACE_VAR=$VAR/iface
		IFACE_REPORT_CONFIG_FILE=\$IFACE_VAR/report.cfg
		IFACE_ORDER_CONFIG_FILE=\$IFACE_VAR/order.cfg
		IFACE_REPORT_MATCHING_CONFIG_FILE=\$IFACE_VAR/reportmatching.cfg
		IFACE_ORDER_MATCHING_CONFIG_FILE=\$IFACE_VAR/ordermatching.cfg
		IFACE_ORDER_GROUPING_CONFIG_FILE=\$IFACE_VAR/ordergrouping.cfg
		SCHEDULER_MSGFLAG_DIR=\$IFACE_VAR/schedulermsg

	EndOfInlineData
} #do_shell_()


# Checks if releasereference.cfg contains handlers
# for Scheduler Module specific references (update messages), and add them if necessery
check_and_add_releasecfg_()
{
	if [ ! -f "${CONF}/releasereference.cfg" ] ; then
		sed "s;\$HOME;$HOME;" ${IFACE_HOME}/releasereference.cfg >> ${CONF}/releasereference.cfg
	else
		# create grep pattern from existing configuration
		GREPP=`awk -vORS=" " '/^#/ {next} ($1 != "") {print "-e ^" $1}' $CONF/releasereference.cfg`
		# make sure that $CONF/releasereference.cfg is writable
		chmod u+w $CONF/releasereference.cfg
		eval "grep -v -e ^# $GREPP ${IFACE_HOME}/releasereference.cfg" | sed "s;\$HOME;$HOME;" >> $CONF/releasereference.cfg
	fi
}

#
# Removes configuration files left over by retired features
# 
remove_retired_() {
	if [ -e "${VAR}/hl7" ] ; then
		# var/hl7 may exist on early v8 servers
		rm -fr "${VAR}/hl7"
	fi
	# http API has also retired, remove old config, if any
	[ -f "${IFACE_VAR}/access.cfg" ] && rm "${IFACE_VAR}/access.cfg" 
}


do_start_()
{
	[ ! -d "$IFACE_VAR" ] && mkdir $IFACE_VAR 2>/dev/null
	[ ! -d "$SCHEDULER_MSGFLAG_DIR" ] && mkdir "$SCHEDULER_MSGFLAG_DIR" 2>/dev/null

	check_and_add_releasecfg_

	remove_retired_

	# TODO: retire IFACE_REPORT_CONFIG_FILE and IFACE_ORDER_CONFIG_FILE

	if [ ! -f "$IFACE_REPORT_CONFIG_FILE" ] ; then
		cat <<-END_OF_REPORT_CFG >> $IFACE_REPORT_CONFIG_FILE
			# Default Config File
			LOCAL - - - - - -
		END_OF_REPORT_CFG
	fi

	if [ ! -f "$IFACE_ORDER_CONFIG_FILE" ] ; then
		cat <<-END_OF_ORDER_CFG >> $IFACE_ORDER_CONFIG_FILE
			# Default Config File
			LOCAL - - - - - -
		END_OF_ORDER_CFG
	fi

} #do_start_()

do_stop_()
{
}


do_beforesubmit_()
{
	do_stop_

} #do_beforesubmit_()

do_aftersubmit_()
{
	do_start_

} #do_aftersubmit_()


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

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

check_action_ $1
if [ 0 = $? ]; then
	cmd=$1
	shift
	do_${cmd}_ "$@"

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

fi
