#!/bin/sh
########################################################################
# Begin $/opt/midas/bin/launch-script
#
# Description : Launch the application
#
# Authors     : Stefan Cook
#
# Version     : 00.00
#
# Notes       : Do necessary house keeping and launch the application
#
########################################################################

. /etc/rc.d/init.d/functions
. /opt/midas/bin/check-setup

# Launch the shutdown monitor daemon.
/opt/midas/bin/shutdown-monitor &

#/sbin/ip link set dev lo multicast on
#/sbin/ip route add 224.0.0.0 dev lo

# Don't try to start the MC if opt/midas var isn't mounted.
# We'd only fill up the ramdisk.
if [ ! -n "`mount | grep /opt/midas/var`" ]; then
    echo "/opt/midas/var is not mounted"
    exit 1
fi

# If application didn't stop respawn
if [ ! -e /var/norespawn ]; then
	
	 # paranoid deletion of old-style marmaserver logs (BIR-488)
    find /opt/midas/var/logs/marmaserver -name "*.log" -type f -delete || true &> /dev/null

	#
	# Start the MC on a GUI/MC platform; i.e. for now a DL3.
	#
	
	# find out what to launch
	whatami TYPE ID
	
	# and launch it
	if [ "${ID}" != "?" ]; then

		checksetup DL2 ${TYPE}
		if [ ${RETVAL} -ne 0 ]; then
			echo "/mnt/disc-on-chip and/or /opt/midas/var failed to mount correctly, refusing to start MC"
			exit 1
		fi
				
		# Create preset library template always (see SBP-268)
		PRESET_LIBRARY_FILE=/opt/midas/var/templates/default.presets
		./mastercontroller create-preset-library-template ${PRESET_LIBRARY_FILE}
		
		# Create show template always (see SBP-268)
		SHOW_FILE=/opt/midas/var/templates/default.show
		./mastercontroller create-show-template ${SHOW_FILE}

		# Create /opt/midas/var/system folder if it does not exist
		if [ ! -d /opt/midas/var/system ]; then
			mkdir /opt/midas/var/system
		fi
		# Create symlink to UK-localtime file if localtime doesn't exist 
		if [ ! -e /opt/midas/var/system/localtime ]; then
			ln -s /etc/UK-localtime /opt/midas/var/system/localtime
		fi
		
		# If configured for diagnostic execution then enable signal handling
		grep --silent /opt/midas/var/logs /etc/syslog.conf
		if [ $? -eq 0 ]; then
			# Ensure the crash directory exists
			if [ ! -d /opt/midas/var/logs/crash ]; then
				mkdir /opt/midas/var/logs/crash
			fi
			
			# Start MC with signal handling enabled.
			taskset -c 0 /opt/midas/bin/mastercontroller run-active enable-signal-handler enable-cache
		else
			# Normal startup
			taskset -c 0 /opt/midas/bin/mastercontroller run-active enable-cache
		fi
	fi
fi

# If not respawning
if [ -e /var/norespawn ]; then
	# drop to bash
	/sbin/agetty -I '\033(K' ttyS0 9600
fi

