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

# 至少要有 3 個參數：<reward_activity's_parameter> <environment> <world_id_lists> [...]
[ -z "$3" ] && {
    echo "Usage: $0 <reward_activity's_parameter> <environment> <world_id_lists> [...]" >&2
    exit 1
}

# 第一個參數: CGI_Command
cgi_command="$1"

if [[ ${cgi_command} =~ ^[0-9]+\+[0-9]+\+[0-9]+$ ]]; then
    echo "${cgi_command}'s Pattern is correct!"
else
    exec echo "${cgi_command}'s Pattern is wrong."
fi

cgi_command_convert=$(echo ${cgi_command} | sed 's/+/ /g')
cgi_log_text=",,reward_activity ${cgi_command_convert}"
shift

# 第二個參數: 環境
environment="$1"
shift

# 其餘參數：world_id_lists
world_id_lists="$*"

# 檢查 environment 合法性
case "$environment" in
    live|LIVE)
        ENVIRONMENT="正式機"
        SCRIPT1="send_chatbot_text_only"
        SCRIPT2="send_messages"
        ;;
    merge|MERGE)
        ENVIRONMENT="合併機"
        SCRIPT1="send_chatbot_text_only_test"
        SCRIPT2="send_messages_test"
        ;;
    test|TEST)
        ENVIRONMENT="測試機"
        SCRIPT1="send_chatbot_text_only_test"
        SCRIPT2="send_messages_test"
        ;;
    data|DATA)
        ENVIRONMENT="資料機"
        SCRIPT1="send_chatbot_text_only_test"
        SCRIPT2="send_messages_test"
        ;;
    time1|TIME1)
        ENVIRONMENT="TIME1"
        SCRIPT1="send_chatbot_text_only_test"
        SCRIPT2="send_messages_test"
        ;;
    submit|SUBMIT)
        ENVIRONMENT="送審機"
        SCRIPT1="send_chatbot_text_only_test"
        SCRIPT2="send_messages_test"
        ;;
    *)
        echo "Unknown environment: ${environment} (only 'test' or 'live' or 'merge' or 'data' or 'time1' or 'submit' allowed)" >&2
        exit 1
        ;;
esac


# 建立搜尋結果 log 檔
LOG_FILE="/tmp/reward_activity_monitor.log"
{
    echo "==============================================="
    echo "Open Activity log check start: $(date)"
    echo "Environment      : ${environment}"
    echo "World ID lists: ${world_id_lists}"
    echo "Log file         : ${LOG_FILE}"
    echo "Retry policy     : max 5 times, interval 3 seconds"
    echo "==============================================="
} > "$LOG_FILE"

# 重試相關設定
MAX_RETRY=5
SLEEP_SEC=3

all_ok=1  # 只要有任何 world 有問題就設為 0

for world_id in ${world_id_lists}; do
    SET_ID=$(( world_id / 100 ))
    CGI_CMD="reward_activity+${world_id}+${cgi_command}"

    # 依環境與 SET_ID 設定 MS_MACHINE & WS_MACHINE
    if [[ ${environment,,} == "merge" ]]; then
        if   [ "${SET_ID}" -ge 10 ] && [ "${SET_ID}" -lt 20 ]; then
            MS_MACHINE="MERGE_ASIA"
            WS_MACHINE="MERGE_ASIA"
        elif [ "${SET_ID}" -ge 20 ] && [ "${SET_ID}" -lt 30 ]; then
            MS_MACHINE="MERGE_US"
            WS_MACHINE="MERGE_US"
        elif [ "${SET_ID}" -ge 30 ] && [ "${SET_ID}" -lt 40 ]; then
            MS_MACHINE="MERGE_EU"
            WS_MACHINE="MERGE_EU"
        else
            echo "Unknown SET_ID ${SET_ID} for test environment" >&2
            echo "[ERROR] world_id=${world_id}, SET_ID=${SET_ID}: unknown SET_ID for test" >> "$LOG_FILE"
            all_ok=0
            continue
        fi
    elif [[ ${environment,,} == "test" ]]; then
        MS_MACHINE="TEST"
        WS_MACHINE="TEST"
    elif [[ ${environment,,} == "data" ]]; then
        MS_MACHINE="DATA"
        WS_MACHINE="DATA"
    elif [[ ${environment,,} == "time1" ]]; then
        MS_MACHINE="TIME1"
        WS_MACHINE="TIME1"
    elif [[ ${environment,,} == "submit" ]]; then
        MS_MACHINE="SUBMIT"
        WS_MACHINE="SUBMIT"
    elif [[ ${environment,,} == "live" ]]; then
        MS_MACHINE="MS${SET_ID}"
        WS_MACHINE="WS${world_id}"
    fi

    # 由 /etc/hosts 取得 IP
    #IP=$(awk -v h="${MS_MACHINE}" '$0 ~ h {print $1}' /etc/hosts | head -n 1)
    IP=$(getent hosts "$MS_MACHINE" | awk '{print $1; exit}')
    if [ -z "$IP" ]; then
        echo "Cannot find IP for machine '${MS_MACHINE}' in /etc/hosts" >&2
        echo "[ERROR] world_id=${world_id}, MS_MACHINE=${MS_MACHINE}: IP not found in /etc/hosts" >> "$LOG_FILE"
        all_ok=0
        continue
    fi

    # 由機器上 setup.ini 取得 Mission CGI Port
    PORT=$(ssh "${MS_MACHINE}" "grep '^CGIPort=' \"\$HOME/servers${SET_ID}/MissionServer${SET_ID}/setup.ini\" 2>/dev/null | sed 's/CGIPort=//'")
    if [ -z "$PORT" ]; then
        echo "Cannot get CGIPort from ${MS_MACHINE}:\$HOME/servers${SET_ID}/MissionServer${SET_ID}/setup.ini" >&2
        echo "[ERROR] world_id=${world_id}, MS_MACHINE=${MS_MACHINE}: CGIPort not found in setup.ini" >> "$LOG_FILE"
        all_ok=0
        continue
    fi

    echo "Machine: ${MS_MACHINE} => IP: ${IP}, Mission: MS${SET_ID}, World: WS${world_id}, Port: ${PORT}"
    echo "curl http://127.0.0.1/cgi-bin/CGIAgent.fcgi?${IP},${PORT},0KjaM85BjfqjA,${CGI_CMD}"
    curl http://127.0.0.1/cgi-bin/CGIAgent.fcgi?${IP},${PORT},0KjaM85BjfqjA,${CGI_CMD}

    {
        echo "-------------------------------------------------------"
        echo "world_id = ${world_id}"
        echo "SET_ID   = ${SET_ID}"
        echo "MS_MACHINE  = ${MS_MACHINE}"
        echo "WS_MACHINE  = ${WS_MACHINE}"
        echo "IP       = ${IP}"
        echo "PORT     = ${PORT}"
        echo "CGI_CMD  = ${CGI_CMD}"
        echo "Check log pattern: '${cgi_log_text}'"
        echo "Retry: max=${MAX_RETRY}, interval=${SLEEP_SEC}s"
    } >> "$LOG_FILE"

    # 重試檢查 GM log
    found=0
    attempt=1
    while [ "$attempt" -le "$MAX_RETRY" ]; do
        echo "World ${world_id}: check log attempt ${attempt}/${MAX_RETRY}..." | tee -a "$LOG_FILE"

        if ssh "${WS_MACHINE}" "cd \"\$HOME/servers${SET_ID}/WorldServer${world_id}\" 2>/dev/null && \
            grep -q '${cgi_log_text}' GM${world_id}.log.* 2>/dev/null"
        then
            echo "World ${world_id}: found '${cgi_log_text}' in GM${world_id}.log.* (OK at attempt ${attempt})"
            echo "[OK]    World ${world_id}: found '${cgi_log_text}' in GM${world_id}.log.* (attempt ${attempt})" >> "$LOG_FILE"
            found=1
            break
        else
            echo "World ${world_id}: NOT found '${cgi_log_text}' in GM${world_id}.log.* (attempt ${attempt})" | tee -a "$LOG_FILE"
            # 若尚未達最大重試次數，睡眠後再試
            if [ "$attempt" -lt "$MAX_RETRY" ]; then
                sleep "$SLEEP_SEC"
            fi
        fi

        attempt=$((attempt + 1))
    done

    if [ "$found" -eq 0 ]; then
        echo "World ${world_id}: FAILED after ${MAX_RETRY} attempts" | tee -a "$LOG_FILE" >&2
        all_ok=0
    fi

    echo "------------------------------------------------------------" >> "$LOG_FILE"
    echo "------------------------------------------------------------"
done

OUTPUT_CGI_CMD="reward_activity+\${world_id}+${cgi_command}"
if [ "$all_ok" -eq 1 ]; then
    echo "全部 world 的 GM log 都已在 ${MAX_RETRY} 次內找到 '${cgi_log_text}'，完成"
    echo "詳細搜尋紀錄請見：${LOG_FILE}"
    $SCRIPT1 "[${ENVIRONMENT}] CGI: ${OUTPUT_CGI_CMD} 成功!" "${world_id_lists}"
    exit 0
else
    echo "部分 world 的 GM log 在 ${MAX_RETRY} 次重試後仍未找到 '${cgi_log_text}'，請檢查詳細搜尋紀錄：" >&2
    echo "LOG_FILE = ${LOG_FILE}" >&2
    echo "================= 搜尋紀錄開始 =================" >&2
    cat "$LOG_FILE" >&2
    echo "================= 搜尋紀錄結束 =================" >&2
    $SCRIPT2 ERROR reward_activity "[${ENVIRONMENT}] CGI: ${OUTPUT_CGI_CMD} 失敗! ${world_id_lists}"
    exit 1
fi

