#!/bin/bash

# viene chiamato prima di start X per disabilitare touch da filtrare
# e poi viene richiamato con parametro start_filter_mode dal set_hid_filter per installare filtri

LIST=/tmp/list$$
XORG_CONF=/tmp/80-disable-filtered-touch.conf
XORG_CONF_LINK=/usr/share/X11/xorg.conf.d/80-disable-filtered-touch.conf
INPUT_FILTER=systools/input_filter

case $1 in
  start_filter) start_filter_mode=1 ;;
  clean)        rm -f $XORG_CONF; exit 0 ;;
esac

ln -nfs $XORG_CONF $XORG_CONF_LINK
cd /opt/euro-beta
source systools/touch_lib

if [ "$start_filter_mode" ]
then
#  killall input_filter
  ps auxw | egrep 'input_filter.*/dev/input' | grep -v grep | awk '{print $2}' | xargs kill 2>/dev/null
else
  rm $XORG_CONF
  patch_old_calibration
fi

function wait_for_install
{
  for ((i=0; i<20; i++))
  do
    sleep 0.1
    xinput list | egrep -q "$1" && return
  done
}


function install_filter
{
  ID=`echo "$1" | cut -d' ' -f1`
  PAR=`echo "$1" | cut -d' ' -f2-`
  cat $LIST | grep $ID |
  while read e
  do
    EVENT=`echo "$e" | cut -f1 -d $'\t'`
    NAME=`echo "$e" | cut -f3 -d $'\t'`
    if [ "$start_filter_mode" ]
    then
#      echo "$INPUT_FILTER --daemon --name \"filtered $NAME\" $PAR /dev/input/$EVENT ">/tmp/install_filter_log
      $INPUT_FILTER --daemon --name "filtered $NAME" $PAR /dev/input/$EVENT
#      wait_for_install 'filtered_touchscreen_input'$EVDEV
    else  
    cat >>$XORG_CONF <<EOF
Section "InputClass"
        Identifier "filtered devices blacklist"
#        MatchProduct    "$NAME"
        MatchDevicePath "/dev/input/$EVENT"
        Option "Ignore" "on"
EndSection
EOF
    fi
  done
}

# get vendor:product and name for every input device
for i in /sys/class/input/event*
do
  echo -e "`basename $i`\t`cat $i/device/id/vendor`:`cat $i/device/id/product`\t`cat $i/device/name`"
done  >$LIST


# install filter for every device listed in input_filter.conf
for id in `cat $LIST | cut -f2 -d $'\t' | sort | uniq`
do
  PATCH=`egrep ^$id input_filter.conf`
  if [ "$PATCH" ]
  then
#    echo found patch $PATCH
    install_filter "$PATCH"
  fi
done

rm -f $LIST
