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

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

SCRIPT_NAME=$(basename "$0")
LOCK_FILE="/tmp/.${SCRIPT_NAME}.lock"

exec 200>"${LOCK_FILE}"
flock -n 200 || {
                echo "${SCRIPT_NAME} is running. Exiting."
    exit 1
}

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

env=$1
ENV_TAG=$(get_env_tag_output ${env})
table_name="fortune_bag"
table_name_output="${table_name} (福袋表)"
output_filename="/tmp/fb_id_set_sequence_monitor.log"

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} ..."

		# 檢查
		COUNT=$(psql -U postgres ${ACCOUNT_DB_NAME} -c "COPY (WITH t1 AS (SELECT id, set, sequence, COUNT(*) FROM ${table_name} GROUP by id, set, sequence HAVING COUNT(*) > 1 ORDER BY id, set, sequence) SELECT COUNT(*) FROM t1) TO STDOUT")

		# 輸出
		if [ "${COUNT}" -ne 0 ]; then
			OUTPUT=$(psql -U postgres ${ACCOUNT_DB_NAME} -c "COPY (SELECT id, set, sequence, COUNT(*) FROM ${table_name} GROUP by id, set, sequence HAVING COUNT(*) > 1 ORDER BY id, set, sequence) TO '${output_filename}' CSV HEADER")
			send_messages ERROR fb_id_set_sequence "${ENV_TAG} 福袋表 ID & SET & SEQUENCE 資料重複 異常"
		fi

		break
	fi
done

