#!/bin/bash


DB_HOST=`cat eurodb.ini | grep Host | cut -d'=' -f2`
if [ "$DB_HOST" != "127.0.0.1" -o "$DB_HOST" != "localhost" ]
then
  MYSQL_ASK="mysql -u euro3g -h $DB_HOST -BNrpeuro3g eurotest"
else
  MYSQL_ASK="mysql -u euro3g -BNrpeuro3g eurotest"
fi

disp_send()
{
  source /opt/euro-beta/euro3g_remote_display.config

  counter_val=$1
  if [ $counter_val -lt 0 ]
  then
    counter_val=0;
  fi
  if [ $counter_val -gt 999 ]
  then
    counter_val=999;
  fi

  for e3g_disp in ${EURO3G_REMOTE_DISPLAY_ADDRESS_ARRAY[*]}
  {
    echo -en $counter_val | nc $e3g_disp 7755
  }
}

{
while sleep 2;
do 
CURR_COUNTER=`systools/get_eurodb_config_val DeliveryMonitorCounter`
DELIVERY_STOCK=`echo 'SELECT FLOOR(SUM(stock)) FROM newplu LEFT JOIN department on department.dept_id = newplu.dept WHERE !category AND !ingredient AND delivery_monitor="1"' | $MYSQL_ASK`
ORDER_STOCK=`echo 'SELECT FLOOR(SUM(order_qty)) FROM objednavka LEFT JOIN newplu ON newplu.plucode = objednavka.plu_id LEFT JOIN department on department.dept_id = newplu.dept WHERE order_idx<1000 AND !category AND !ingredient AND delivery_monitor="1"'| $MYSQL_ASK`
DELIVERY_SUM=`systools/get_eurodb_config_val DeliveryStockSum`
NEW_COUNTER=$(( $DELIVERY_SUM - $ORDER_STOCK + $DELIVERY_STOCK ))
if [ "$CURR_COUNTER" != "$NEW_COUNTER" ]
then
  systools/set_eurodb_config_val DeliveryMonitorCounter int $NEW_COUNTER
  disp_send $NEW_COUNTER
fi
done
} &
