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

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

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

#--- FUNC ------------------------------
do_shell_()
{
	cat <<-EndOfInlineData
		DOTCOM_HOME=$HOME/component/dotcom
	EndOfInlineData

} #do_shell_()


do_crontab_()
{
	# Get time from crontabSchedule settings for starting recollect dotcom info
	[ -f "$CONF/crontabSchedule.shi" ] && . $CONF/crontabSchedule.shi
	
	if has_role_ "application" ; then
	
		[ -z "$ReCollectDotcom" ] && ReCollectDotcom="18 01"
		# Get time from crontabSchedule settings for sending timestamp
		[ -z "$SendTime" ] && SendTime="01-56/5 *"

		cat <<-EOI
			$ReCollectDotcom * * * $TASKD_HOME/runjavacmd -c "0 dotcom.ReCollect" -p $JAVA_SERVER_PORT
			$SendTime * * * $DOTCOM_HOME/sendtime.sh >/dev/null 2>&1
		EOI
	fi
}

generate_empty_jcfg_()
{
	echo "Creating empty dotcom configuration"

	[ -f "$CONF/serverid.cfg" ] && . "$CONF/serverid.cfg"

	cat <<-EOF > $CONF/dotcom.jcfg
<DotcomConfig>
	<DeviceTable>
		<DotcomDevice>
			<ID>  $SELF_SERVER_ID </ID>
	        </DotcomDevice>
	</DeviceTable>
</DotcomConfig>
<!--
    INITIAL DOTCOM.JCFG
-->
EOF
}

do_start_()
{

	if [ ! -f "$CONF/serverid.cfg" ] ; then
		echo "Generating self ID"
		$DOTCOM_HOME/createselfid.sh
	fi

	# Start recollect if no dotcom.jcfg exists
	if [ ! -f "$CONF/dotcom.jcfg" ]; then
		generate_empty_jcfg_
	fi
	
	if [ -f "$CONF/dotcom.jcfg" ] && grep -q "INITIAL DOTCOM.JCFG" "$CONF/dotcom.jcfg"; then
		echo "queuing re-collecting dotcom configuration"
		$TASKD_HOME/createchildtask.sh -p "RECOLLECT_DOTCOM_INFO" -t "class" -c "dotcom.ReCollect"
	fi

    # link classes into $HOME/htdocs/WEB-INF/classes
    if [ ! -h $HOME/htdocs/WEB-INF/classes ] ; then
        CWD=`pwd`
        cd $HOME/htdocs/WEB-INF/classes
        if [ ! -h $HOME/htdocs/WEB-INF/classes/dotcom ] ; then
            ln -s $DOTCOM_HOME/classes/dotcom
        fi
        cd $CWD
    fi
}

#
# List files/tables to be backed up grouped by categories
#
# output lines should be in '<category> <type> <names>' format
#
do_listbackup_()
{
	# This file can be re-generated - do it in afterrestore
	cat <<-EOFLISTBACKUP
		nobackup.nobackup FILE ${CONF#$HOME/}/dotcom.jcfg
	EOFLISTBACKUP
}

do_setup_()
{
	if [ ! -f "$CONF/serverid.cfg" ] ; then
		echo "Generating self ID"
		$DOTCOM_HOME/createselfid.sh
	fi

	if [ ! -f "$CONF/dotcom.jcfg" ] ; then
		generate_empty_jcfg_
	fi
}

#--- MAIN ------------------------------
check_action_ $1
if [ 0 = $? ]; then
	do_$1_

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

fi
