#!/bin/bash
source $HOME/.gamerc
[ "$1" == "" ] && exec echo "Usage: $0 <TAG>"

TAG=$1
[ ! -z $TAG ] && CONDITIONAL_STATEMENT_1=" AND tag = '$TAG'"; CONDITIONAL_STATEMENT_2=" AND mail_name = '$TAG'"
OUTPUT="/tmp/xl_event_send_reward_by_system_output.csv"

[ -f $OUTPUT ] && sudo rm -rf $OUTPUT

CHECK_CNT=$(psql -U postgres $ACCOUNT_DB_NAME -c "COPY (SELECT COUNT(*) FROM xl_event_send_reward_by_system WHERE status = 0 $CONDITIONAL_STATEMENT_1) TO STDOUT;")

if [ "$CHECK_CNT" -gt 0 ]; then
	psql -U postgres $ACCOUNT_DB_NAME -c "COPY (SELECT account_name, item_id, item_quantity, tag as mail_name, 0 as point FROM xl_event_send_reward_by_system WHERE status = 0 $CONDITIONAL_STATEMENT_1 ORDER BY account_name) TO '$OUTPUT' CSV;"
	psql -U postgres $ACCOUNT_DB_NAME -c "COPY item_receivable (account_name, item_id, item_quantity, mail_name, point) FROM '$OUTPUT' CSV;"
	psql -U postgres $ACCOUNT_DB_NAME -c "UPDATE xl_event_send_reward_by_system t1 SET status = 1, sent_datetime = NOW(), last_updated_datetime = NOW() FROM item_receivable t2 WHERE status = 0 $CONDITIONAL_STATEMENT_1 AND (t1.account_name, t1.item_id, t1.item_quantity, t1.tag) IN (SELECT account_name, item_id, item_quantity, mail_name FROM item_receivable WHERE 1=1 $CONDITIONAL_STATEMENT_2);"
else
	if [ ! -z $TAG ]; then
		echo "No reward queues for $TAG!"
	else
		echo "No reward queues!"
	fi
fi
