#!/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 &

# eisenma - test multicast setup for loopback device
#/sbin/ip link set dev lo multicast on
#/sbin/ip route add 224.0.0.0 dev lo

# If application didn't stop respawn
if [ ! -e /var/norespawn ]; then
	
	#
	# 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 DL3 MC
		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

		# Extract the dsp projects file to this folder for the mastercontroller
		tar -zxf /opt/midas/bin/projects/targets.tar.gz -C /mnt/disc-on-chip/projects

		# Create preset library template if it doesn't exist
		PRESET_LIBRARY_FILE=/opt/midas/var/templates/default.presets
		if [ ! -e ${PRESET_LIBRARY_FILE} ]; then
			./mastercontroller create-preset-library-template ${PRESET_LIBRARY_FILE}
		fi
		
		# Create show template if it doesn't exist
		SHOW_FILE=/opt/midas/var/templates/default.show
		if [ ! -e ${SHOW_FILE} ]; then
			./mastercontroller create-show-template ${SHOW_FILE}
		fi
		# 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 DSP discovery agent not already started
		if [ -z "`ps -AH | grep pandad`" ]; then
			# start it
			/opt/midas/bin/pandad -d &
		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 0x00000002 /opt/midas/bin/mastercontroller enable-signal-handler enable-cache
		else
			# Normal startup
			taskset 0x00000002 /opt/midas/bin/mastercontroller enable-cache
		fi
	fi
fi

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

