# !/bin/sh

# Setup path veriables
SCRIPTS_PATH=/Insight/Scripts

# Turn on USB power
echo "Turning on USB Power"
echo 78 > /sys/class/gpio/export
echo out > /sys/class/gpio/gpio78/direction
echo 1 > /sys/class/gpio/gpio78/value

echo Configuring eth0: 100baseT/full/AN-off
ethtool -s eth0 speed 100 duplex full autoneg off

FIRMWARE_INFO_FILE=/Insight/firmware.info
if [[ -f ${FIRMWARE_INFO_FILE} ]]; then
        FIRMWARE_VERSION_STRING=$(grep Firmware ${FIRMWARE_INFO_FILE})
        # extract the version field
        FIRMWARE_VERSION=$(echo ${FIRMWARE_VERSION_STRING} | cut -d '"' -f4)
        # extract the version letter
        VERSION_LETTER=${FIRMWARE_VERSION:6:1}
        # check if less than the version with USB enumeration
        # wait built into SystemMonitor (rev H)
        FIRMWARE_FILE_PRESENT=true
        echo "/Insight/firmware.info file present"
else
        FIRMWARE_FILE_PRESENT=false
        echo "/Insight/firmware.info file absent"
fi

# Determine if we need to wait for USB to enumerate
if [[ ! ${FIRMWARE_FILE_PRESENT} ]] || [[ ${VERSION_LETTER} < 'H' ]]; then
                echo
                echo "Firmware Version = ${FIRMWARE_VERSION}"
                echo "Version Letter = '$VERSION_LETTER'"
                echo "Version letter is less than H"
                echo "Wait for USB to enumerate"
                echo
				sleep 4
fi

# FirmwareUpdateResetHelper.sh only exists after a firmware update (kernel update)
# It's purpose is to restore settings and remove update files from SD
# The application removes this or performs a new update if it is not present
# This prevents an update from running on a reboot from an update.
if [ -f "$SCRIPTS_PATH/FirmwareUpdateResetHelper.sh" ]; then
	# Run FirmwareUpdateResetHelper.sh once then delete it
	$SCRIPTS_PATH/FirmwareUpdateResetHelper.sh
	# FirmwareUpdateResetHelper.sh is a run once script.  Delete it

	echo "insightStartup.sh removing Insight/Scripts/FirmwareUpdateResetHelper.sh"
	# Remove the script now that it has executed so it won't
	# run on the next reset.
	rm $SCRIPTS_PATH/FirmwareUpdateResetHelper.sh
fi

echo 
echo "**---> Starting System Monitor <---**"
echo
/Insight/Applications/SystemMonitor
