#!/usr/bin/env bash
set -x

# Wait for the processing board, as it's the last usb device to be enumerated. If e.g. a user has
# a crappy usb key which times out when probed, this can delay the enumeration of the surface boards
# and touch screens.

# Set the number of touchscreens based on the unit type written into .UnitType by the TLDSurface app.
# Depending on the unit type, wait for either left or both touchscreens to become available.
# See Identity.h in TLDSurface project for the unit type enumerator.

Count=20
NoOfTouchScreens=0
FILE="/home/tld/.UnitType"

if [ -f "$FILE" ]; then
   s=$(<$FILE)
else
   s=0
fi

case $s in
9)  # TLD_120_SURFACE
	NoOfTouchScreens=1
	;;
10) # TLD_168_SURFACE
	NoOfTouchScreens=2
	;;
11) # TLD_216_SURFACE
	NoOfTouchScreens=2
	;;
12) # DLC_1500_SURFACE
	NoOfTouchScreens=1
	;;
13) # DLC_2500_SURFACE
	NoOfTouchScreens=1
	;;
14) # DLC_3500_SURFACE
	NoOfTouchScreens=2
	;;
15) # TLD_UNKNOWN_SURFACE
	NoOfTouchScreens=2
	;;
*)	# Default
	NoOfTouchScreens=2
	;;
esac

if [ "$NoOfTouchScreens" == 1 ]; then
	echo "Single TouchScreen Surface Detected" > /home/tld/.TypeCheck
	while [[ (! -e /dev/ah_processing || ((! -e /dev/input/ts_left) && (! -e /dev/input/tse_left))) && ! $Count -lt 0 ]]
	do
  	   sudo sh -c 'echo "waiting for processing board and touchscreen" > /dev/kmsg'
	   echo "$Count" >> /home/tld/.TypeCheck
  	   Count=$((Count - 1))
 	   sleep 1
	done
else 
	echo "Dual TouchScreen Surface Detected" > /home/tld/.TypeCheck
	while [[ (! -e /dev/ah_processing || ((! -e /dev/input/ts_left) && (! -e /dev/input/tse_left)) || ((! -e /dev/input/ts_right) && (! -e /dev/input/tse_right))) && ! $Count -lt 0 ]]
	do
  	   sudo sh -c 'echo "waiting for processing board and touchscreens..." > /dev/kmsg'
	   echo "$Count" >> /home/tld/.TypeCheck
  	   Count=$((Count - 1))
  	   sleep 1 
	done
fi

if (( $Count < 0 )); then
  sudo sh -c 'echo "Timed out waiting for processing board and touchscreen..." > /dev/kmsg'
  echo "Time out" >> /home/tld/.TypeCheck
fi
