#!/bin/bash
########################################################################
# 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
export HOME=/root
. ${HOME}/.profile

# Check if X server is running yet
if [ ! `pidof X` ]; then
    sleep 1
    exit 0
fi

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

# If application didn't stop respawn
if [ ! -e /var/norespawn ]; then
	
	#
	# Start the GUI on a GUI/MC platform
	#
	
	# find out what to launch
	whatami TYPE ID
	
	# and launch it
	if [ "${ID}" != "?" ]; then
		checksetup DL2 ${TYPE}
		if [ ${RETVAL} -gt 1 ]; then
			echo "Both /mnt/disc-on-chip and /opt/midas/var failed to mount correctly, refusing to start GUI"
			exit 1
		fi
		
		# start the GUI
		if [ ! -e /var/cache-sod-check-complete ]; then
			# pause on initial startup to reduce contension.
			sleep 1
		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 GUI with signal handling enabled.
			taskset -c 1 /opt/midas/bin/marmaset enable-signal-handler > /dev/console 2>&1
		else
			# Normal startup
            taskset -c 1 /opt/midas/bin/marmaset > /dev/console 2>&1
		fi
	fi
fi

# If not respawning
if [ ! -e /var/autoupdate ]; then
	if [ -e /var/runupdater ]; then
	    mkdir -p /mnt/disc-on-chip/keycopy
	    rm -r -f /mnt/disc-on-chip/Updater
	    cd /mnt/disc-on-chip/;  tar --no-same-owner --occurrence -xf $(cat /var/runupdater) Updater
	    /mnt/disc-on-chip/Updater /mnt/disc-on-chip/DL3Update > /dev/null
	    # now clear our temporary files, leaving the keycopy directory
	    rm -r -f /mnt/disc-on-chip/keycopy/*
	    rm -r -f /mnt/disc-on-chip/Updater
	fi
fi

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


