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

[ -z "$3" ] && {
    echo "Usage: $0 <environment> <target_world_id> <source_world_id1> [source_world_id2 ...]" >&2
    exit 1
}

environment="$1"
shift

target_world_id="$1"
shift

source_world_ids="$*"

# ===== 原樣保留 =====
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

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
OPEN_ACTIVITY_FILE="${SCRIPT_DIR}/merge_activity_open_parameters"
[ ! -f "${OPEN_ACTIVITY_FILE}" ] && {
    echo "Cannot find ${OPEN_ACTIVITY_FILE}" >&2
    exit 1
}

OPEN_ACTIVITY_IDS=$(grep -v '^[[:space:]]*$' "${OPEN_ACTIVITY_FILE}" | tr '\n' ' ' | sed 's/[[:space:]]*$//')
[ -z "${OPEN_ACTIVITY_IDS}" ] && {
    echo "No valid open activity parameters found in ${OPEN_ACTIVITY_FILE}" >&2
    exit 1
}

LOG_FILE="/tmp/open_activity_cgi_monitor.log"
{
    echo "==============================================="
    echo "Open activity log check start: $(date)"
    echo "Environment       : ${environment}"
    echo "Target world id   : ${target_world_id}"
    echo "Source world list : ${source_world_ids} (informational only)"
    echo "Open activity file: ${OPEN_ACTIVITY_FILE}"
    echo "Open activity ids : ${OPEN_ACTIVITY_IDS}"
    echo "Log file          : ${LOG_FILE}"
    echo "Retry policy      : max ${MAX_RETRY} times, interval ${SLEEP_SEC} seconds"
    echo "==============================================="
} > "$LOG_FILE"

all_ok=1

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

    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

    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

    PORT=$(ssh "${MS_MACHINE}" "grep '^CGIPort=' \"\$HOME/servers${SET_ID}/MissionServer${SET_ID}/setup.ini\" 2>/dev/null | sed 's/CGIPort=//'" < /dev/null)
    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

    exec 3< "${OPEN_ACTIVITY_FILE}"
    while IFS= read -r CGI_Command <&3; do
        [ -z "${CGI_Command}" ] && continue

        if [[ ! ${CGI_Command} =~ ^[0-9]+\+[0-9]+\+[0-9]+$ ]]; then
            echo "CGI_Command format wrong: ${CGI_Command}" >&2
            echo "[ERROR] world_id=${world_id}, CGI_Command=${CGI_Command}: format wrong" >> "$LOG_FILE"
            world_ok=0
            continue
        fi

        cgi_command_convert=$(echo "${CGI_Command}" | sed 's/+/ /g')
        CGI_CMD="open_activity+${world_id}+${CGI_Command}"
        GREP_PATTERN=",,open_activity ${cgi_command_convert}"

        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" < /dev/null; then
            echo "World ${world_id} open_activity ${CGI_Command}: already found '${GREP_PATTERN}' in log, SKIP"
            echo "[SKIP]  World ${world_id} open_activity ${CGI_Command}: 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}" < /dev/null; 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} open_activity ${CGI_Command}: curl FAILED after 3 attempts, aborting" | tee -a "$LOG_FILE"
            $SCRIPT2 ERROR open_activity_cgi "[${ENVIRONMENT}合併] CGI: open_activity 失敗! world_id=${world_id} curl failed"
            exit 1
        fi

        {
            echo "-------------------------------------------------------"
            echo "world_id          = ${world_id}"
            echo "CGI_Command       = ${CGI_Command}"
            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} open_activity ${CGI_Command}: 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" < /dev/null
            then
                echo "World ${world_id} open_activity ${CGI_Command}: found '${GREP_PATTERN}' (attempt ${attempt})"
                echo "[OK] World ${world_id} open_activity ${CGI_Command}: found (attempt ${attempt})" >> "$LOG_FILE"
                found=1
                break
            else
                echo "World ${world_id} open_activity ${CGI_Command}: NOT found (attempt ${attempt})" | tee -a "$LOG_FILE"
                [ "$attempt" -lt "$MAX_RETRY" ] && sleep "$SLEEP_SEC"
            fi

            attempt=$((attempt + 1))
        done

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

    done
    exec 3<&-

    [ "$world_ok" -eq 0 ] && all_ok=0

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

if [ "$all_ok" -eq 1 ]; then
    echo "全部 world 的 GM log 都已找到 open_activity，完成"
    echo "詳細搜尋紀錄請見：${LOG_FILE}"
    $SCRIPT1 "[${ENVIRONMENT}合併] CGI: open_activity (${OPEN_ACTIVITY_IDS}) 成功!" "${target_world_id}"
    exit 0
else
    echo "部分 world 的 GM log 未找到 open_activity，請檢查：" >&2
    echo "LOG_FILE = ${LOG_FILE}" >&2
    cat "$LOG_FILE" >&2
    $SCRIPT2 ERROR open_activity_cgi "[${ENVIRONMENT}合併] CGI: open_activity (${OPEN_ACTIVITY_IDS}) 失敗! ${target_world_id}"
    exit 1
fi
