#!/bin/bash
cd `dirname $0`
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games
export PATH
trap 'false' SIGHUP
trap 'false' SIGTERM

TC_E3G_LOGFILE="/opt/euro-beta/log/touchcal.log"

function calculate_matrix # calib_out_file
{
  out=`cat $1`
  device_name=$(sed -n 's/.*MatchProduct\s*"\([^"]*\)".*/\1/p' <<< "$out")

  wtot=$(sed -n 's/.*max_x=\([0-9]*\).*/\1/p' <<< "$out")
  htot=$(sed -n 's/.*max_y=\([0-9]*\).*/\1/p' <<< "$out")

  calib=$(sed -n 's/.*Option.*"Calibration"\s*"\([-0-9 ]*\).*/\1/p' <<< "$out")
  minx=$(cut -d' ' -f1  <<< "$calib")
  maxx=$(cut -d' ' -f2  <<< "$calib")
  miny=$(cut -d' ' -f3  <<< "$calib")
  maxy=$(cut -d' ' -f4  <<< "$calib")

  swapxy=$(grep 'Option.*"SwapAxes"\s*"1"' <<< "$out")
  wtouch=$(bc <<< "$maxx - $minx")
  htouch=$(bc <<< "$maxy - $miny")
  odd=`[ $(( $wtouch * $htouch )) -lt 0 ] && echo 1` # 1 if odd number of axes are inverted

  a=$(bc -l <<< "scale=4; $wtot / $wtouch")
  b=$(bc -l <<< "scale=4; -1 * $minx / $wtouch")
  c=$(bc -l <<< "scale=4; $htot / $htouch")
  d=$(bc -l <<< "scale=4; -1 * $miny / $htouch")

  if [ ! "$swapxy" ]
  then
    tf_matrix="$a 0 $b 0 $c $d 0 0 1"
  else 
    if [ "$odd" ]
    then
      a=$(bc -l <<< "scale=4; -1 * $a")
      b=$(bc -l <<< "scale=4; $maxx / $wtouch")
      c=$(bc -l <<< "scale=4; -1 * $c")
      d=$(bc -l <<< "scale=4; $maxy / $htouch")
    fi
    tf_matrix="0 $c $d $a 0 $b 0 0 1"
  fi

#alter the setting for now
#  xinput set-prop "$device" 'Coordinate Transformation Matrix' $tf_matrix

echo "Section \"InputClass\""
echo "	Identifier \"calibration\""
echo "	MatchProduct \"$device_name\""
echo "	Option \"TransformationMatrix\" \"$tf_matrix\""
echo "EndSection"
}

#only for test
#calculate_matrix /tmp/xinput_calibration.out
#exit 0

cd /opt/euro-beta
source systools/touch_lib

install_input_filter
if [ "$1" ]
then
  MSGPAR="-m"
fi
TRY_HID=0
echo "./touchquery -i \"`search_touch_devices`\" /dev/ttyS?   2>/tmp/touchquery.log" >/tmp/touchquery.command
TOUCH_DETECT=$( strace -t -f -o /tmp/touchquery.strace ./touchquery $MSGPAR "$1" -i "`search_touch_devices`" /dev/ttyS?   2>/tmp/touchquery.log)
case $? in
  0) 
      TRY_HID=1
      ;; 
  
  1) 
      echo "$TOUCH_DETECT" > e3g_inputattach
      ;;
      
  2)
      rm -f e3g_inputattach
      TOUCH_DEVICE=`echo "$TOUCH_DETECT" | head -1` # fixme - se sara' piu' di uno?
      ;;
esac

echo "First touchcal finished" >>/tmp/touchquery.log
if [ $TRY_HID -eq 1 ]
then
  echo "./touchquery -i \"`search_touch_devices`\" -m \"Per la calibrazione dei dispositivi non standard ( hidraw ) toccare qui\" /dev/hidraw?   2>>/tmp/touchquery.log" >>/tmp/touchquery.command
  TOUCH_DETECT=$(./touchquery $MSGPAR "$1" -i "`search_touch_devices`" -m "Per la calibrazione dei dispositivi non standard ( hidraw ) toccare qui" /dev/hidraw?   2>>/tmp/touchquery.log)
  case $? in
    0) 
        exit  1 # no touch - no calibrate
        ;; 
  
    1) 
        echo "$TOUCH_DETECT" > e3g_inputattach
        ;;
        
    2)
        TOUCH_DEVICE=`echo "$TOUCH_DETECT" | head -1` # fixme - se sara' piu' di uno?
        ;;
  esac
fi


install_inputattach #installa eventuale non-hid touch sulla seriale

# we must wait a bit before new input device can be reliably detected 
sleep 1

EVDEV=$TOUCH_DEVICE
if [ ! "$EVDEV" ] 
then
  EVDEV=`search_touch_devices | head -1`
fi  
RANGE=`systools/input_filter --getRange $EVDEV`
echo $RANGE
if [ "$RANGE" ]
then
  PRECALIB="--precalib $RANGE"
fi

ID=`find_device_id $EVDEV`
if [ "$ID" ] 
then
  DEVID="--device $ID"
fi

CONF=/tmp/xinput_calibration.conf
OUT=/tmp/xinput_calibration.out
[ -f $CONF ] && rm $CONF 
{
  echo xinput set-float-prop $ID "Coordinate Transformation Matrix" 1, 0, 0, 0, 1, 0, 0, 0, 1
  echo "systools/xinput_calibrator $PRECALIB $DEVID --output-type xorg.conf.d --output-filename $CONF > $OUT 2>/tmp/xinput_calibration.err" 
} >/tmp/xinput_calibration.run
xinput set-float-prop $ID "Coordinate Transformation Matrix" 1, 0, 0, 0, 1, 0, 0, 0, 1
systools/xinput_calibrator $PRECALIB $DEVID --output-type xorg.conf.d --output-filename $CONF > $OUT 2>/tmp/xinput_calibration.err

calculate_matrix $OUT > $CONF

#if grep -q "Making the calibration permanent" /tmp/xinput_calibration.log
#then 
#  cat /tmp/xinput_calibration.log | grep -A10 "Section \"InputClass\"" > /usr/share/X11/xorg.conf.d/99-calibration.conf
#fi

[ -f $CONF ] && cp  $CONF /usr/share/X11/xorg.conf.d/99-calibration.conf
touch /tmp/touchscreen_calibrated
echo `date`": Touchscreen calibration invoked by user ..." >> $TC_E3G_LOGFILE
echo "--------------- Touchquery command ---------------" >> $TC_E3G_LOGFILE
cat /tmp/touchquery.command >> $TC_E3G_LOGFILE
echo "--------------- Touchquery output ---------------" >> $TC_E3G_LOGFILE
cat /tmp/touchquery.log >> $TC_E3G_LOGFILE
echo "--------------- xinput_calibration input ---------------" >> $TC_E3G_LOGFILE
cat /tmp/xinput_calibration.conf >> $TC_E3G_LOGFILE
echo "--------------- xinput_calibration output ---------------" >> $TC_E3G_LOGFILE
cat /tmp/xinput_calibration.out >> $TC_E3G_LOGFILE
echo "--------------- xinput_calibration err ---------------" >> $TC_E3G_LOGFILE
cat /tmp/xinput_calibration.err >> $TC_E3G_LOGFILE
echo "--------------- xinput_calibration err ---------------" >> $TC_E3G_LOGFILE
cat /tmp/xinput_calibration.err >> $TC_E3G_LOGFILE

exit 0
