#!/bin/sh

# SPDX-License-Identifier: GPL-2.0
# Copyright (C) 2016-present Team LibreELEC (https://libreelec.tv)

# change vid/pid for waveshare touchscreen device
PRODUCT_VID=0EEF
PRODUCT_PID=0005

# device set directly or find automaticaly at the end of this script
export TSLIB_TSDEVICE=""
#export TSLIB_TSDEVICE="/dev/hidrawN"

export TSLIB_PLUGINDIR=$ADDON_DIR/lib
export TSLIB_CONSOLEDEVICE=none
export TSLIB_FBDEVICE=/dev/fb0
export TSLIB_CALIBFILE=/storage/.kodi/userdata/addon_data/service.touchscreen/pointercal
export TSLIB_CONFFILE=/storage/.kodi/userdata/addon_data/service.touchscreen/ts.conf

export TSLIB_RES_X=800
export TSLIB_RES_Y=480


# find touchscreen device
if [ "$TSLIB_TSDEVICE" = "" ]; then
  PRODUCT_VID_PID="0000${PRODUCT_VID}:0000${PRODUCT_PID}"
  echo "PRODUCT_VID_PID: $PRODUCT_VID_PID"

  hidrawN=""
  for dev in /sys/class/hidraw/hidraw*/device/uevent; do
    echo
    echo "device: $dev"

    HID_ID=$(cat $dev | grep HID_ID | grep "$PRODUCT_VID_PID")
    if [ -n "$HID_ID" ]; then
      hidrawN=$(echo $dev | awk -F "/" '{print $5}')
      hidrawN="/dev/$hidrawN"
      echo "OK HID_ID: $HID_ID"
      echo "OK hidrawN: $hidrawN"
      break
    fi
  done

  if [ -n "$hidrawN" ]; then
    echo "found hidrawN: $hidrawN"
    export TSLIB_TSDEVICE=$hidrawN
  fi
fi
