#!/bin/bash

if [ ! -e "/opt/pos/common/data/custom_scripts/rfid_balance.sh" ]; then
  ln -s /opt/pos/common/bin/rfid/rfid_balance.sh /opt/pos/common/data/custom_scripts/rfid_balance.sh
fi

LOG=1
LOG_FILE="/opt/pos/server/data/rfid.log"
COUNT_ERROR=0

while [ true ]; do
  NOW=`date +%Y%m%d_%H%M%S`
  LOG_PREFIX="rfid_daemon.sh,$NOW,$$"

  DEVICE_ID1=`ls /sys/bus/usb/drivers/ch341 | grep "-"`

  # kill any rfid process pending
  ps xa | grep rfid | grep -v daemon | grep -v grep | awk '{ print $1 }' | xargs kill -9 2> /dev/null

  /opt/pos/common/bin/rfid/rfid_daemon empty 0.00 0000

  DEVICE_ID2=`ls /sys/bus/usb/drivers/ch341 | grep "-"`

  if [ ! -e "/dev/ttyUSB0" ] && [ ! -e "/dev/ttyUSB1" ]; then
    COUNT_ERROR=`expr $COUNT_ERROR + 1`

    if [ $LOG -eq 1 ] && [ $COUNT_ERROR -le 10 ]; then
      echo "$LOG_PREFIX, ENDED, NO /dev/ttyUSB0 AND /dev/ttyUSB1, DEVICE_ID1: $DEVICE_ID1, DEVICE_ID2: $DEVICE_ID2" >> $LOG_FILE
    fi

    if [ "$DEVICE_ID1" != "" ]; then
      echo -n "$DEVICE_ID1" > /sys/bus/usb/drivers/ch341/unbind
      echo -n "$DEVICE_ID1" > /sys/bus/usb/drivers/ch341/bind
    elif [ "$DEVICE_ID2" != "" ]; then
      echo -n "$DEVICE_ID2" > /sys/bus/usb/drivers/ch341/unbind
      echo -n "$DEVICE_ID2" > /sys/bus/usb/drivers/ch341/bind
    fi
  else
    COUNT_ERROR=0
  fi

  sleep 1
done

