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

TAG=$1
[ ! -z $TAG ] && CONDITIONAL_STATEMENT_1=" WHERE tag = '$TAG'"; CONDITIONAL_STATEMENT_2=" WHERE mail_name = '$TAG'"

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

if [ "$CHECK_CNT" -gt 0 ]; then
	psql -U postgres $ACCOUNT_DB_NAME -c "UPDATE xl_event_send_reward_by_system t1 SET status = 2, last_updated_datetime = NOW() FROM item_receipt t2 $CONDITIONAL_STATEMENT_1 AND (t1.account_name, t1.item_id, t1.item_quantity) IN (SELECT account_name, item_id, item_quantity FROM item_receipt);"
	psql -U postgres $ACCOUNT_DB_NAME -c "UPDATE xl_event_send_reward_by_system t1 SET status = -1, deleted_datetime = NOW(), last_updated_datetime = NOW() FROM item_receivable t2 $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 $CONDITIONAL_STATEMENT_2);"
	psql -U postgres $ACCOUNT_DB_NAME -c "DELETE FROM item_receivable $CONDITIONAL_STATEMENT_2;"
else
	echo "Empty Data."
fi
