# Initialise Touch Screen
. /home/ubuntu/PersistentData/ScreenCalibration.sh

# Files
UPDATE_FIRMWARE_REQUESTED_FILE=/home/ubuntu/.update_requested
PERFORM_FIRMWARE_UPDATE_FILE=/home/ubuntu/.perform_update
FIRMWARE_SHUTDOWN_SUCCESSFULLY_FILE=/home/ubuntu/.shutdown_successful
DEBUG_MODE_FILE=/home/ubuntu/.ah_debug
USB_DEBUG_MODE_FILE=/mnt/usb-storage/AllenHeathGLD/ah_debug
USB_FORCE_FIRMWARE_UPDATE=/mnt/usb-storage/AllenHeathGLD/force_update
REBOOT_REQUIRED_FILE=/home/ubuntu/.reboot_required

# Applications
BOOT_STRAP_APP=/home/ubuntu/iGL-Bootloader
UPDATE_FIRMWARE_APP=/mnt/usb-storage/AllenHeathGLD/Firmware/Updater/iGL-Updater
MAIN_FIRMWARE_APP="/home/ubuntu/iGL-Firmware"
MAIN_FIRMWARE_APP_RUN="/home/ubuntu/iGL-Firmware nodialog -graphicssystem raster"

# We can request a boot bypass to get a prompt by touching a debug file in ~ or usb
if [ -e $DEBUG_MODE_FILE -o -e $USB_DEBUG_MODE_FILE ] ; then
  # This is an upstart signal which triggers the sshd to start. Look in /etc/init/sshd.conf for more details.
  sudo initctl emit ah_debug
  # Display a local terminal
  xterm -geometry 130x45
else
  # Otherwise test if an update has been requested, or the main firmware is missing, or we didn't boot successfully
  if [ -e $UPDATE_FIRMWARE_REQUESTED_FILE -o -e $USB_FORCE_FIRMWARE_UPDATE -o ! -e $MAIN_FIRMWARE_APP -o ! -e $FIRMWARE_SHUTDOWN_SUCCESSFULLY_FILE ] ; then
    # Call Boot Strap Application
    $BOOT_STRAP_APP
    # Remove Update Request File - so we boot correctly next time.
    rm $UPDATE_FIRMWARE_REQUESTED_FILE > /dev/null 2>&1
  fi

  if [ -e $PERFORM_FIRMWARE_UPDATE_FILE ] ; then
    # Either of the above could trigger an update.
    $UPDATE_FIRMWARE_APP
    # Clear up Update File
    rm $PERFORM_FIRMWARE_UPDATE_FILE > /dev/null 2>&1
    # Force a disk sync - the application write may not be finished !
    sync
  fi

  if [ -e $REBOOT_REQUIRED_FILE ] ; then 
    sudo rm $REBOOT_REQUIRED_FILE
    sudo shutdown -r now
    sleep 15
  else
    # Now launch the Application. If it doesn't exist, we go around again.
    if [ -e $MAIN_FIRMWARE_APP ] ; then
      # Clear up the Shutdown successfully last time file
      rm $FIRMWARE_SHUTDOWN_SUCCESSFULLY_FILE > /dev/null 2>&1
      # Run the Main App.
      $MAIN_FIRMWARE_APP_RUN
    fi

  fi
fi











