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

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

env=$1
if [ "${env}" == "0" ]; then
    ENV_TAG="(測試)"
elif [ "${env}" == "1" ]; then
    ENV_TAG="(正式)"
fi

DATA="/tmp/check_open_activity_data"
OUTPUT_1="/tmp/check_open_activity_mapping_table_monitor.log"
OUTPUT_2="/tmp/check_open_activity_id_exist_monitor.log"

#[[ -f "${DATA}" ]] && rm -rf ${DATA}
[[ -f "${OUTPUT_1}" ]] && rm -rf ${OUTPUT_1}
[[ -f "${OUTPUT_2}" ]] && rm -rf ${OUTPUT_2}

# 定義對應表 (用 associative array)
declare -A map_table_name=(
  [1]="activity_consume"
  [2]="activity_days_mission_store_group"
  [4]="activity_mission_store_group"
  [5]="activity_rank_event_schedule"
  [6]="activity_mission_battle_pass_group"
  [10]="activity_accruebuy_schedule"
)

declare -A map_cht_name=(
  [1]="累積消費活動表"
  [2]="七日任務商店表"
  [4]="任務商店總表"
  [5]="衝榜活動表"
  [6]="任務通行證總表"
  [10]="階段付費時程表"
)

# 輸出 $HOME/common-TEST/Data/db/s_resetservercmds.ini > open_activity 的資料
awk -F"|" '$1 ~/^[0-9]+$/ {print $2}' $HOME/common-TEST/Data/db/s_resetservercmds.ini | awk -F" " '$1 ~/^open_activity *$/ {print $2","$3","$4}' | grep -v -E '^0,'  > $DATA

# 讀取 $DATA
while IFS=, read -r key col2 col3; do
    if [[ -z "${map_table_name[$key]}" ]]; then
        echo "$key,$col2,$col3" >> $OUTPUT_1
    else
        echo "$key 對應 ${map_table_name[$key]} (其他欄=$col2,$col3)"
    fi

    TABLE_NAME="${map_table_name[$key]}"
    CHT_NAME="${map_cht_name[$key]}"
    ID_CHECK="$col2"
    if [ ! -z "${TABLE_NAME}" ]; then
        RECORD=$(psql -U postgres ${ACCOUNT_DB_NAME} -c "COPY (SELECT COUNT(*) FROM ${TABLE_NAME} WHERE id = $col2) TO STDOUT;")
        if [ "${RECORD}" -eq 0 ]; then
            echo "$key,$col2,$col3" >> $OUTPUT_2
            echo "ID: $col2 不存在於資料表 ${TABLE_NAME} ( ${CHT_NAME} ) 中" >> $OUTPUT_2
        fi
    fi
done < $DATA

OUTPUT_1="/tmp/check_open_activity_mapping_table_monitor.log"
OUTPUT_2="/tmp/check_open_activity_id_exist_monitor.log"

if [ -f "${OUTPUT_1}" ]; then
    LOG_SIZE_1=$(stat --printf="%s" ${OUTPUT_1})
    if [ "${LOG_SIZE_1}" -gt 0 ]; then
        send_messages ERROR check_open_activity_mapping_table "${ENV_TAG} open_activity 新增編號 企劃沒有通知系統對應資料表!"
    fi
fi

if [ -f "${OUTPUT_2}" ]; then
    LOG_SIZE_2=$(stat --printf="%s" ${OUTPUT_2})
    if [ "${LOG_SIZE_2}" -gt 0 ]; then
        send_messages ERROR check_open_activity_id_exist "${ENV_TAG} open_activity 資料表 產營填表有問題!"
    fi
fi

