#!/bin/bash

export DISPLAY=:0.0

if [ -f "/tmp/.calibrate_no_display" ]; then
  sleep 3
  xinput_calibrator --output-type xinput > /tmp/cal

  BEFORE=`cat /tmp/cal | tail -1 | cut -d" " -f1-14`
  AFTER=`cat /tmp/cal | tail -1 | cut -d" " -f16-16`
  COORD1=`cat /tmp/cal | tail -1 | cut -d" " -f15`
  COORD2=`cat /tmp/cal | tail -1 | cut -d" " -f17`
  NEW_COORD1=`expr $COORD1 + 4900`
  NEW_COORD2=`expr $COORD2 + 184`
  CMD="$BEFORE $NEW_COORD1 $AFTER $NEW_COORD2"
  DEVICE=`xinput --list | grep RISINTECH | cut -d"=" -f2 | cut -f1 -d$'\t' | tail -1`

  CMD2=`echo "$CMD" | sed "s/\"RISINTECH HID Touch\"/$DEVICE/"`
  echo "$CMD2" > /tmp/cal2
  /opt/bin/replace_token /opt/bin/display.sh.orig "##COORDINATES##" /tmp/cal2 > /opt/bin/display.sh

  rm /tmp/.calibrate_no_display
  killall Xorg
else
  touch /tmp/.calibrate_no_display
  killall Xorg
fi

