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

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

env=$1
correct_filename="/tmp/itemmall_item_price_iap_name_mapping_correct_monitor.log"
output_filename="/tmp/itemmall_item_price_iap_name_monitor.log"

#ACCOUNT_DB_NAME="N1Account_ERR"

psql -U postgres ${ACCOUNT_DB_NAME} -c "DROP TABLE IF EXISTS xl_iap_name_price_mapping; CREATE TABLE xl_iap_name_price_mapping AS (WITH t1 AS (SELECT id, iap_name, (string_to_array(iap_name, '_'))[array_length(string_to_array(iap_name, '_'), 1)] AS last_value, price FROM itemmall_item WHERE iap_name <> '' ORDER BY id), t2 AS (SELECT last_value, price, COUNT(*) FROM t1 GROUP BY last_value, price ORDER BY last_value::INTEGER, count DESC) SELECT DISTINCT ON (last_value::INTEGER) last_value, price FROM t2 ORDER BY last_value::INTEGER, count DESC);"

COUNT=$(psql -U postgres ${ACCOUNT_DB_NAME} -c "COPY (WITH t1 AS (SELECT id, iap_name, (string_to_array(iap_name, '_'))[array_length(string_to_array(iap_name, '_'), 1)] AS last_value, price FROM itemmall_item WHERE iap_name <> '' ORDER BY id) SELECT COUNT(*) FROM t1 WHERE (last_value, price) NOT IN (SELECT last_value, price FROM xl_iap_name_price_mapping)) TO STDOUT;")

if [ "${COUNT}" -ne 0 ]; then
    CORRECT=$(psql -U postgres ${ACCOUNT_DB_NAME} -c "COPY (SELECT * FROM xl_iap_name_price_mapping ORDER BY last_value::INTEGER) TO '${correct_filename}' CSV HEADER")
    OUTPUT=$(psql -U postgres ${ACCOUNT_DB_NAME} -c "COPY (WITH t1 AS (SELECT id, iap_name, (string_to_array(iap_name, '_'))[array_length(string_to_array(iap_name, '_'), 1)] AS last_value, price FROM itemmall_item WHERE iap_name <> '' ORDER BY id) SELECT * FROM t1 WHERE (last_value, price) NOT IN (SELECT last_value, price FROM xl_iap_name_price_mapping) ORDER BY last_value::INTEGER, price) TO '${output_filename}' CSV HEADER")

    if [ "${env}" == "0" ]; then
        ENV_TAG="(測試)"
    elif [ "${env}" == "1" ]; then
        ENV_TAG="(正式)"
    fi
    send_messages REFERENCE itemmall_item_price_iap_name_mapping_correct "${ENV_TAG} 上架表 IAP_NAME 跟價錢對應, 正確版本如下"
    send_messages ERROR itemmall_item_price_iap_name "${ENV_TAG} 上架表 IAP_NAME 跟價錢對應有誤, 請確認!"
fi
