#!/bin/bash
source $HOME/.gamerc

[ "$1" == "" ] && exec echo "Usage: $0 <Environment (TEST => 0, LIVE => 1)>"

if ! type function_loaded &> /dev/null; then
	. ./additional_functions
fi

if ! type send_messages &> /dev/null; then
	send_messages_cmd="./send_messages"
else
	send_messages_cmd="send_messages"
fi

env=$1
ENV_TAG=$(get_env_tag_output ${env})
output_filename="/tmp/payback_vs_powerupitem_item_id_monitor.log"
table_name="payback"
table_name_output="${table_name} (零元返鑽表)"

stop_check=$(check_table_uploading $table_name)
while true; do
	if [ "${stop_check}" -eq 0 ]; then
		echo "Waiting ${table_name_output} ..."
		stop_check=$(check_table_uploading $table_name)
	elif [ "${stop_check}" -eq -1 ]; then
		echo "Quit ${table_name_output} ..."
		break
	elif [ "${stop_check}" -eq 1 ]; then
		echo "Checking ${table_name_output} ..."
		
		# 零元返鑽福袋道具ID
		COUNT1=$(psql -U postgres ${ACCOUNT_DB_NAME} -c "COPY (WITH t1 AS (SELECT DISTINCT item_id FROM payback WHERE item_id NOT IN (SELECT item_id FROM powerupitem) ORDER BY item_id) SELECT COUNT(item_id) FROM t1) TO STDOUT;")

		# 零元返鑽返還道具ID
		COUNT2=$(psql -U postgres ${ACCOUNT_DB_NAME} -c "COPY (WITH t1 AS (SELECT DISTINCT back_item_id AS item_id FROM payback WHERE back_item_id NOT IN (SELECT item_id FROM powerupitem) ORDER BY back_item_id) SELECT COUNT(item_id) FROM t1) TO STDOUT;")

		if [ "${COUNT1}" -ne 0 ]; then
			OUTPUT=$(psql -U postgres ${ACCOUNT_DB_NAME} -c "COPY (WITH t1 AS (SELECT DISTINCT item_id FROM payback WHERE item_id NOT IN (SELECT item_id FROM powerupitem)) SELECT item_id FROM t1 ORDER BY item_id) TO '${output_filename}' CSV HEADER")
			#send_messages ERROR payback_vs_powerupitem_item_id "${ENV_TAG} 零元返鑽表的福袋道具ID 設定版本內未包含的道具ID品項"
			$send_messages_cmd ERROR payback_vs_powerupitem_item_id "${ENV_TAG} 零元返鑽表的福袋道具ID 設定版本內未包含的道具ID品項"
		fi

		if [ "${COUNT2}" -ne 0 ]; then
			OUTPUT=$(psql -U postgres ${ACCOUNT_DB_NAME} -c "COPY (WITH t1 AS (SELECT DISTINCT back_item_id AS item_id FROM payback WHERE item_id NOT IN (SELECT item_id FROM powerupitem)) SELECT item_id FROM t1 ORDER BY item_id) TO '${output_filename}' CSV HEADER")
			#send_messages ERROR payback_vs_powerupitem_item_id "${ENV_TAG} 零元返鑽表的返還道具ID 設定版本內未包含的道具ID品項"
			$send_messages_cmd ERROR payback_vs_powerupitem_item_id "${ENV_TAG} 零元返鑽表的返還道具ID 設定版本內未包含的道具ID品項"
		fi

		break
	fi
done
