#!/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=`

touch /tmp/x64_stop.txt

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
fi

PORT=`cat $CONFIG | grep "X64_PORT" | cut -f2 -d=`
STATION=`cat $CONFIG | grep "STATION_NUMBER" | cut -f2 -d=`
NSI=`cat $CONFIG | grep "NETWORK_SERVER_IP" | cut -f2 -d=`

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

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
fi

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

if [ ! -d "/root/.wine/dosdevices" ]; then
  mkdir /root/.wine/dosdevices
fi

rm -rf /root/.wine/dosdevices/com1
ln -s $PORT /root/.wine/dosdevices/com1

if [ "$STATION" = "0" ]; then
  psql -d pos -o /tmp/out2.csv -U root -c "SELECT handy_plu, name AS plu FROM products WHERE deleted = 0 AND handy_plu ~ '^[0-9]+$' AND char_length(handy_plu) <= 4 AND handy_plu <> '0' LIMIT 1"
else
  psql -d pos -h $NSI -o /tmp/out2.csv -U root -c "SELECT handy_plu, name AS plu FROM products WHERE deleted = 0 AND handy_plu ~ '^[0-9]+$' AND char_length(handy_plu) <= 4 AND handy_plu <> '0' LIMIT 1"
fi

cat /tmp/out2.csv | grep -v "rows" | grep -v "\-\+\-" | grep -v "handy_plu \|           name" > /tmp/out.csv

export DISPLAY=:0.0

if [ "$X64_LICENSE" = "" ]; then
  wine /opt/pos/common/addons/x64/upload_plus.exe
else
  wine /opt/pos/common/addons/x64/upload_plus.exe license=$X64_LICENSE
fi

rm -rf /tmp/out.csv
rm -rf /tmp/out2.csv
rm -rf /tmp/x64_stop.txt


