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

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

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

# 第二個參數：target_world_id（目前未實際使用，如需可加入邏輯）
target_world_id="$1"
shift

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

# 檢查 environment 合法性
case "$environment" in
    test)
        ENVIRONMENT="測試"
        SCRIPT1="send_chatbot_text_only_test"
        SCRIPT2="send_messages_test"
        ;;
    live)
        ENVIRONMENT="正式"
        SCRIPT1="send_chatbot_text_only"
        SCRIPT2="send_messages"
        ;;
    *)
        echo "Unknown environment: ${environment} (only 'test' or 'live' allowed)" >&2
        exit 1
        ;;
esac

# 依 MERGE_MODE + SET_ID 取得 test 環境的機器名
_get_test_machine() {
    local sid="$1"
    case "${MERGE_MODE:-single}" in
        single)
            echo "MERGE"
            ;;
        multiple)
            if   [ "$sid" -ge 10 ] && [ "$sid" -lt 20 ]; then echo "MERGE_ASIA"
            elif [ "$sid" -ge 20 ] && [ "$sid" -lt 30 ]; then echo "MERGE_US"
            elif [ "$sid" -ge 30 ] && [ "$sid" -lt 40 ]; then echo "MERGE_EU"
            else return 1
            fi
            ;;
        *)
            echo "Error: unknown MERGE_MODE '${MERGE_MODE}'" >&2
            return 1
            ;;
    esac
}

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

# 可彈性設定要跑的 reward_id（同一 world 必須全部 OK 才算成功）
REWARD_IDS="5 14"

# 建立搜尋結果 log 檔
LOG_FILE="/tmp/reward_cgi_monitor.log"
{
    echo "==============================================="
    echo "Reward activity log check start: $(date)"
    echo "Environment      : ${environment}"
    echo "Target world id  : ${target_world_id}"
    echo "Source world list: ${source_world_ids}"
    echo "Reward ids       : ${REWARD_IDS}"
    echo "Log file         : ${LOG_FILE}"
    echo "Retry policy     : max ${MAX_RETRY} times, interval ${SLEEP_SEC} seconds"
    echo "==============================================="
} > "$LOG_FILE"

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

for world_id in ${source_world_ids}; do
    SET_ID=$(( world_id / 100 ))

    # 依環境與 SET_ID 設定 MS_MACHINE & WS_MACHINE
    if [ "${environment}" == "test" ]; then
        MS_MACHINE="$(_get_test_machine "$SET_ID")" || {
            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
        }
        WS_MACHINE="$MS_MACHINE"
    elif [ "${environment}" == "live" ]; then
        MS_MACHINE="MS${SET_ID}"
        WS_MACHINE="WS${world_id}"
    fi

    # 由 /etc/hosts 取得 IP
    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

    world_ok=1  # 同一 world 內，只要有任一 reward_id 失敗就變 0

    for reward_id in ${REWARD_IDS}; do
        CGI_CMD="reward_activity+${world_id}+${reward_id}"
        GREP_PATTERN=",,reward_activity ${reward_id}"

        echo "Machine: ${MS_MACHINE} => IP: ${IP}, Mission: MS${SET_ID}, World: WS${world_id}, Port: ${PORT}"

        # 先檢查 log 是否已有結果（重跑時跳過已成功的）
        if ssh "${WS_MACHINE}" "cd \"\$HOME/servers${SET_ID}/WorldServer${world_id}\" 2>/dev/null && \
            grep -q \"${GREP_PATTERN}\" GM${world_id}.log.* 2>/dev/null"; then
            echo "World ${world_id} reward ${reward_id}: already found '${GREP_PATTERN}' in log, SKIP"
            echo "[SKIP]  World ${world_id} reward ${reward_id}: already exists" >> "$LOG_FILE"
            continue
        fi

        # curl 送 CGI，失敗重試 3 次，間隔 5 秒
        CGI_URL="http://127.0.0.1/cgi-bin/CGIAgent.fcgi?${IP},${PORT},0KjaM85BjfqjA,${CGI_CMD}"
        curl_ok=0
        for curl_try in 1 2 3; do
            echo "curl (attempt ${curl_try}/3): ${CGI_URL}"
            if curl --connect-timeout 5 -m 30 -sf "${CGI_URL}"; then
                echo ""
                echo "curl OK (attempt ${curl_try})"
                curl_ok=1
                break
            else
                echo "curl FAILED (attempt ${curl_try})" | tee -a "$LOG_FILE"
                [ "$curl_try" -lt 3 ] && sleep 5
            fi
        done

        if [ "$curl_ok" -eq 0 ]; then
            echo "World ${world_id} reward ${reward_id}: curl FAILED after 3 attempts, aborting" | tee -a "$LOG_FILE"
            $SCRIPT2 ERROR reward_cgi "[${ENVIRONMENT}合併] CGI: reward_activity (${REWARD_IDS}) 失敗! world_id=${world_id} reward_id=${reward_id} curl failed"
            exit 1
        fi

        {
            echo "-------------------------------------------------------"
            echo "world_id  = ${world_id}"
            echo "reward_id = ${reward_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: '${GREP_PATTERN}'"
            echo "Retry: max=${MAX_RETRY}, interval=${SLEEP_SEC}s"
        } >> "$LOG_FILE"

        found=0
        attempt=1
        while [ "$attempt" -le "$MAX_RETRY" ]; do
            echo "World ${world_id} reward ${reward_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 \"${GREP_PATTERN}\" GM${world_id}.log.* 2>/dev/null"
            then
                echo "World ${world_id} reward ${reward_id}: found '${GREP_PATTERN}' in GM${world_id}.log.* (OK at attempt ${attempt})"
                echo "[OK]    World ${world_id} reward ${reward_id}: found '${GREP_PATTERN}' (attempt ${attempt})" >> "$LOG_FILE"
                found=1
                break
            else
                echo "World ${world_id} reward ${reward_id}: NOT found '${GREP_PATTERN}' 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} reward ${reward_id}: FAILED after ${MAX_RETRY} attempts" | tee -a "$LOG_FILE" >&2
            world_ok=0
        fi
    done

    # world AND 判定：所有 reward_id 都要成功，否則整個 world 視為失敗
    if [ "$world_ok" -eq 0 ]; then
        all_ok=0
    fi

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

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