#!/bin/bash

#
# using xinput attaches to the selected device. This was made bacause some
# machines have devices like a PS2 keyboard that didn't appear on evtest
# (which shows only usb devices)
#

export DISPLAY=:0.0

IFS=$'\n'

for line in `xinput | sed 's/[^a-zA-Z 0-9\t]//g'`; do
  ID=`echo $line | cut -f2 | sed 's/id//'`
  ID=$(printf '%3s' $ID)
  NAME=`echo $line | cut -f1 | sed 's/^[ \t]*//' | sed 's/[ \t]*$//'`

  echo "$ID  - $NAME"
done

echo ""
echo "USB device to use? "
read var

num=0

for line in `xinput | sed 's/[^a-zA-Z 0-9\t]//g'`; do
  num=`expr $num + 1`
  ID=`echo $line | cut -f2 | sed 's/id//'`
  NAME=`echo $line | cut -f1 | sed 's/^[ \t]*//' | sed 's/[ \t]*$//'`

  if [ "$ID" = "$var" ]; then
    ps xa | grep read_keys | awk '{ print $1 }' | xargs kill -9 2> /dev/null

    if [ -e "/opt/pos/common/addons/read_usb_keys/etc/device" ]; then
      rm -rf /opt/pos/common/addons/read_usb_keys/etc/device
    fi

    echo "$NAME" > /opt/pos/common/addons/read_usb_keys/etc/device2
    /opt/pos/common/addons/read_usb_keys/bin/read_keys2.sh &
    /opt/bin/kill_pos.sh
  fi
done

