#!/bin/sh

export DISPLAY=:0.0

TOUCH="eGalaxTouch Virtual Device for Single" # check this with "xinput list" and "xinput test"

INIT=$1

if [ "$INIT" != "" ]; then
  # wait for the device to be ready
  while [ 1 -gt 0 ]; do
    HAS=`xinput list | grep "$TOUCH"`

    #echo "### $HAS" >> /tmp/n.txt

    if [ "$HAS" != "" ]; then
      break
    fi

    sleep 1
  done
fi

DISPLAY_MAIN=`/opt/bin/xrandr_devices | head -1 | cut -d, -f1`
DISPLAY_USB=`/opt/bin/xrandr_devices | tail -1 | cut -d, -f1`

TOUCH_ID=`xinput | grep "$TOUCH" | cut -d= -f2 | awk '{ print $1 }'` #  eGalaxTouch Virtual Device for Single

#xinput list >> /tmp/n.txt
#echo "######" >> /tmp/n.txt
#/opt/bin/xrandr_devices >> /tmp/n.txt
#echo "######" >> /tmp/n.txt
#echo "$DISPLAY_MAIN - $DISPLAY_USB - $TOUCH_ID" >> /tmp/n.txt

# means we've an USB display
if [ "$DISPLAY_USB" != "" ] && [ "$DISPLAY_MAIN" != "$DISPLAY_USB" ]; then
  xrandr --output $DISPLAY_USB --off
fi

if [ "$INIT" = "" ]; then
  eCalib Cal
fi

if [ "$DISPLAY_USB" != "" ] && [ "$DISPLAY_MAIN" != "$DISPLAY_USB" ]; then
  xrandr --output $DISPLAY_USB --auto
  xrandr --output $DISPLAY_MAIN --left-of $DISPLAY_USB

  if [ "$TOUCH_ID" != "" ]; then
    xinput map-to-output $TOUCH_ID $DISPLAY_MAIN
  fi
fi

