#!/bin/bash

LOG=1
NOW=`date +%Y%m%d_%H%M%S`
LOG_PREFIX="rfid_balance_web_adjust.sh,$NOW,$$"
LOG_FILE="/opt/pos/server/data/rfid.log"

RFID_TOKEN=`cat /opt/pos/etc/config.ini | grep RFID_TOKEN= | cut -f2 -d=`
RFID_API_PASSWD=`cat /opt/pos/etc/config.ini | grep RFID_API_PASSWD= | cut -f2 -d=`

if [ "$RFID_TOKEN" = "" ] || [ "$RFID_API_PASSWD" = "" ]; then
  exit 0
fi

if [ -e "/opt/pos/common/tmp/rfid_result.txt"]; then
  rm -f /opt/pos/common/tmp/rfid_result.txt
fi

# we need to check how to get this from params
CLERK_ID=1

/opt/pos/common/bin/rfid/rfid_balance.sh $CLERK_ID TO_STDOUT &

COUNT=0
CARD_ID=""

while [ $COUNT -le 10 ]; do
  if [ -e "/opt/pos/common/tmp/rfid_result.txt" ]; then
    CARD_ID=`cat /opt/pos/common/tmp/rfid_result.txt | cut -d"#" -f1`
    break
  fi

  COUNT=`expr $COUNT + 1`
  sleep 1
done

if [ $LOG -eq 1 ]; then
  echo "----------------- BEGIN - $LOG_PREFILOG_PREFIX" >> $LOG_FILE
fi

if [ "$CARD_ID" != "" ]; then
  URL="http://apisv2.net-bo.com/pos_rfid/stats?token=$RFID_TOKEN=&api_passwd=$RFID_API_PASSWD=&card_id=$CARD_ID&generate=1"

  if [ $LOG -eq 1 ]; then
    echo "$LOG_PREFIX, will open $URL" >> $LOG_FILE
  fi

  /opt/bin/keyboard.sh
  sudo -H -u pos bash -c "export DISPLAY=:0.0 ; /usr/bin/chromium-browser --user-data-dir=/home/pos/.chrome \"$URL\""
  /opt/bin/keyboard.sh 1
fi

if [ $LOG -eq 1 ]; then
  echo "----------------- END - $LOG_PREFIX" >> $LOG_FILE
fi

exit 0

