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

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

env=$1
output_filename="/tmp/fb_id_set_sequence_monitor.log"

# 檢查
COUNT=$(psql -U postgres ${ACCOUNT_DB_NAME} -c "COPY (WITH t1 AS (SELECT id, set, sequence, COUNT(*) FROM fortune_bag 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 fortune_bag GROUP by id, set, sequence HAVING COUNT(*) > 1 ORDER BY id, set, sequence) TO '${output_filename}' CSV HEADER")

    if [ "${env}" == "0" ]; then
        ENV_TAG="(測試)"
    elif [ "${env}" == "1" ]; then
        ENV_TAG="(正式)"
    fi
    send_messages ERROR fb_id_set_sequence "${ENV_TAG} 福袋表 ID & SET & SEQUENCE 資料重複 異常"
fi
