#!/bin/bash

ID=$1           # single id
MODIF_DATE=$2   # since this modif date
IDS=$3          # multiple ids

STATION=`cat /opt/pos/etc/config.ini | grep "STATION_NUMBER=" | cut -d= -f2`
DB_IP="127.0.0.1"

DIR=""

if [ "$STATION" = "0" ]; then
  DIR="/opt/pos/server/data/glabels"
else
  DIR="/shares/pos/server/data/glabels"
fi

# gen one id only
if [ "$ID" != "" ]; then
  psql -h $DB_IP -U root -AF',' -d pos -c "SELECT id, REPLACE(name, ',', '') AS name, REPLACE(button_text, ',', '') AS button_text, button_color, button_bg_color, sell_price1, sell_price2, sell_price3, sell_price4, sell_price5, sell_price_menu, sell_vat1, sell_vat2, is_weight, REPLACE(barcode, ',', ';') AS barcode, ask_price FROM products WHERE deleted = 0 AND barcode <> '' AND barcode <> '--' AND barcode <> '0' AND id = '$ID' ORDER BY id" > $DIR/products.$STATION.csv
elif [ "$IDS" != "" ]; then
  psql -h $DB_IP -U root -AF',' -d pos -c "SELECT id, REPLACE(name, ',', '') AS name, REPLACE(button_text, ',', '') AS button_text, button_color, button_bg_color, sell_price1, sell_price2, sell_price3, sell_price4, sell_price5, sell_price_menu, sell_vat1, sell_vat2, is_weight, REPLACE(barcode, ',', ';') AS barcode, ask_price FROM products WHERE deleted = 0 AND barcode <> '' AND barcode <> '--' AND barcode <> '0' AND id IN ($IDS) ORDER BY id" > $DIR/products.$STATION.csv
# gen for all the products
else
  if [ "$STATION" != "0" ]; then
    DB_IP=`cat /opt/pos/etc/config.ini | grep "NETWORK_SERVER_IP=" | cut -d= -f2`
  fi

  SQL="SELECT id, REPLACE(name, ',', '') AS name, REPLACE(button_text, ',', '') AS button_text, button_color, button_bg_color, sell_price1, sell_price2, sell_price3, sell_price4, sell_price5, sell_price_menu, sell_vat1, sell_vat2, is_weight, REPLACE(barcode, ',', ';') AS barcode, ask_price FROM products WHERE deleted = 0 AND barcode <> '' AND barcode <> '--' AND barcode <> '0'"

  if [ "$MODIF_DATE" != "" ]; then
    SQL="$SQL AND modified >= '$MODIF_DATE'"
  fi

  SQL="$SQL ORDER BY id"

  psql -h $DB_IP -U root -AF',' -d pos -c "$SQL" > $DIR/products.$STATION.csv
fi

sed -i '$ d' $DIR/products.$STATION.csv


