#!/bin/bash

KILL=$1
CONFIG="/opt/pos/etc/config.ini"
LOG_FILE="/root/logs/x64.log"
X64_LICENSE=`cat $CONFIG | grep "X64_LICENSE" | cut -f2 -d=`

if [ "$KILL" != "" ]; then
  PID=`ps -eo pid,args | grep x64\.gambas | grep -v grep | cut -c1-6`

  if [ "$PID" != "" ]; then
    echo "Will kill PID $PID"
    kill -9 $PID 2> /dev/null
    exit
  fi

  echo "Can't find PID..."
  exit
fi

while [ 1 ]; do
  if [ ! -e "/tmp/x64_stop.txt" ]; then
    if [ -d "/opt/pos/common/addons/x64" ]; then
      if [ -e "/opt/pos/common/addons/x64/x64.gambas" ]; then
        PORT=`cat $CONFIG | grep "X64_PORT" | cut -f2 -d=`
        #STATION=`cat $CONFIG | grep "STATION_NUMBER" | cut -f2 -d=`
        #echo "1" > /opt/pos/common/tmp/restart_hardware_handlers#$STATION.txt

        if [ "$PORT" = "" ]; then
          PORT="/dev/ttyS0"
        fi

        CUR_DATE=`date +%Y%m%d_%H%M%S`
        echo "[$CUR_DATE] X64 START - $PORT" >> $LOG_FILE

        if [ ! -e "$PORT" ]; then
          echo "[$CUR_DATE] X64 ERROR - Can't find port $PORT" >> $LOG_FILE

          if [[ $PORT =~ "USB" ]]; then
            if [ -e "/dev/ttyUSB0" ]; then
              PORT="/dev/ttyUSB0"
            elif [ -e "/dev/ttyUSB1" ]; then
              PORT="/dev/ttyUSB1"
            elif [ -e "/dev/ttyUSB2" ]; then
              PORT="/dev/ttyUSB2"
            fi
          fi

          echo "[$CUR_DATE] X64 PORT RETRY - WILL TRY PORT - $PORT" >> $LOG_FILE

          if [ ! -e "$PORT" ]; then
            echo "[$CUR_DATE] X64 ERROR - Can't find port $PORT" >> $LOG_FILE
          else
            export DISPLAY=:0.0
            echo "[$CUR_DATE] Will start X64 - $PORT..." >> $LOG_FILE
            /opt/pos/common/bin/x64_init_antena.sh
            /opt/pos/common/addons/x64/x64.gambas port=$PORT
          fi
        else
          export DISPLAY=:0.0
          echo "[$CUR_DATE] Will start X64 - $PORT..." >> $LOG_FILE
          /opt/pos/common/bin/x64_init_antena.sh
          /opt/pos/common/addons/x64/x64.gambas port=$PORT
        fi
      fi
    fi
  fi

  sleep 2
done

