#!/usr/bin/env bash
# Initialise Touch Screen

# Files
UPDATE_FIRMWARE_REQUESTED_FILE=/home/tld/.update_requested
PERFORM_FIRMWARE_UPDATE_FILE=/home/tld/.perform_update
FIRMWARE_SHUTDOWN_SUCCESSFULLY_FILE=/home/tld/.shutdown_successful
DEBUG_MODE_FILE=/home/tld/.ah_debug
USB_DEBUG_MODE_FILE=/mnt/usb-storage/AllenHeath-dLive/ah_debug
USB_FORCE_FIRMWARE_UPDATE=/mnt/usb-storage/AllenHeath-dLive/force_update
REBOOT_REQUIRED_FILE=/home/tld/.reboot_required
AUTO_UPDATE_TEST=/home/tld/.auto_update_test
AUTO_UPDATE_TEST_LOG=/home/tld/auto_update_test_log.txt

# Applications
BOOT_STRAP_APP=/home/tld/bin/TLD-Bootloader
UPDATE_FIRMWARE_APP=/mnt/usb-storage/AllenHeath-dLive/Firmware/Updater/Updater
MAIN_FIRMWARE_APP="/home/tld/bin/TLDSurface"
MAIN_FIRMWARE_APP_RUN="/home/tld/bin/TLDSurface --gui"
PRODUCTION_TEST_APP=/mnt/usb-storage/ah_dLive_production_test

# Configure Video
xrandr --output DP2 --mode 2048x768
xrdb ~/.Xresources

# Setup XInput
/home/tld/bin/setupXInput.sh

# Enable the vga hotplug script and run for the first time
# Note that running for the first time here also means that tmp files are owned by tld not root
touch /tmp/vga-hotplug-script-enabled
/home/tld/bin/vga-hotplug-worker.sh

/home/tld/bin/mouse-hotplug.sh

while [ 1 ]
do
  # 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 340x59
  elif [ -e $PRODUCTION_TEST_APP ] ; then
    # Else allow production test code to run if it exists, 
    # could do this in a term which persists but might want to allow all options for testing
    # xterm -geometry 340x59 -hold -e $PRODUCTION_TEST_APP
    # So let called code decide
    $PRODUCTION_TEST_APP
  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
    fi
    
    if [ -e $PERFORM_FIRMWARE_UPDATE_FILE -o -e $USB_FORCE_FIRMWARE_UPDATE ] ; then
      # Either of the above could trigger an update.
      if [ -e $AUTO_UPDATE_TEST ] ; then 
        # Look in /mnt/usb-storage for AllenHeath-dLive-*.** and if any exist, select a random version

        selected=`ls /mnt/usb-storage | grep "^AllenHeath-dLive-[0-9]\.[0-9][0-9]" | awk 'BEGIN { i = 0 } { words[i] = $0; i++ } END { srand(); if(i>0) { print words[int(rand() * i)] } }'`
        if [ ! -z "$selected" ] ; then
          rm -rf /mnt/usb-storage/AllenHeath-dLive
          cp -pr /mnt/usb-storage/$selected /mnt/usb-storage/AllenHeath-dLive
          sync
          echo Selected version $selected >> $AUTO_UPDATE_TEST_LOG
        fi

        echo `date` Updater starting >> $AUTO_UPDATE_TEST_LOG
        $UPDATE_FIRMWARE_APP --AutoUpdateTest >> $AUTO_UPDATE_TEST_LOG 2>&1
        echo `date` Updater finished >> $AUTO_UPDATE_TEST_LOG
      else
        $UPDATE_FIRMWARE_APP
      fi
      # 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
    elif [ -e $UPDATE_FIRMWARE_REQUESTED_FILE ] ; then
      echo "Retrying update"
      # Do nothing. Let it loop back round into the updater part.
    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.
        if [ -e $AUTO_UPDATE_TEST ] ; then 
          $MAIN_FIRMWARE_APP_RUN --AutoUpdateTest >> Surface.out 2>&1
        else
          $MAIN_FIRMWARE_APP_RUN
        fi
        killall TLDTouchScreen
      fi
    fi
  fi
done
