#!/bin/bash
########################################
# mrtg_manager — MRTG 設定管理工具
#
# 用法:
#   mrtg_manager init       <set_id> <ws_start> <ws_end>   # 首次建 Zone（建目錄 + header + common + world）
#   mrtg_manager add        <set_id> <ws_start> <ws_end>   # 新增 World（append world）
#   mrtg_manager remove     <set_id>                        # 合併移除（依 fake_worlds 刪除）
#   mrtg_manager auto       <set_id> <ws_start> <ws_end>   # 自動判斷（目錄不存在 → init，存在 → add）
#
# 所有操作最後都會自動跑 fix_mrtg_info
########################################

source "$HOME/.gamerc"

########################################
# MRTG lockfile race 處理
# cron 排程會週期性呼叫 mrtg，與本腳本的 fix_mrtg_info 可能撞車
########################################

# 等待 MRTG lockfile 消失（cron 的 mrtg 跑完會自己刪 lockfile）
_wait_for_mrtg_lock() {
    local lockfile="$1"
    local timeout="${2:-60}"
    local elapsed=0
    while [[ -f "$lockfile" && $elapsed -lt $timeout ]]; do
        sleep 2
        elapsed=$((elapsed + 2))
    done
    [[ -f "$lockfile" ]] && return 1 || return 0
}

# fix_mrtg_info 包 retry：遇到 lockfile race 自動等 + 重試
_run_fix_mrtg_info() {
    local set_id="$1"
    local cfg_file="$2"
    local lockfile="${cfg_file}_l"
    local max_attempts=5
    local retry_delay=10
    local output rc

    for ((i=1; i<=max_attempts; i++)); do
        if [[ -f "$lockfile" ]]; then
            echo "  偵測到 mrtg lockfile（$lockfile），等待最多 60s..."
            _wait_for_mrtg_lock "$lockfile" 60 || true
        fi

        output=$($HOME/bin/fix_mrtg_info ${set_id} ${cfg_file} 2>&1)
        rc=$?
        echo "$output"

        # 成功 = exit 0 且輸出沒出現 "another mrtg is running"
        if [[ $rc -eq 0 ]] && ! echo "$output" | grep -q "another mrtg is running"; then
            return 0
        fi

        if [[ $i -lt $max_attempts ]]; then
            echo "  MRTG busy，第 ${i}/${max_attempts} 次失敗，${retry_delay}s 後重試..." >&2
            sleep $retry_delay
        fi
    done

    echo "  ERROR: fix_mrtg_info 重試 ${max_attempts} 次仍失敗" >&2
    return 1
}

LOWER_GAME_TYPE="${GAME_TYPE,,}"
LOWER_COUNTRY_CODE="${COUNTRY_CODE,,}"
PROJECT_DIRECTORY="${LOWER_GAME_TYPE}${LOWER_COUNTRY_CODE}"
# 去掉 WEBTOOL_ROOT_DIRECTORY 結尾的 /，避免雙斜線
_WEBTOOL_ROOT="${WEBTOOL_ROOT_DIRECTORY%/}"
MRTG_BASE="${_WEBTOOL_ROOT}/mrtgx_${PROJECT_DIRECTORY}"

usage() {
    echo "用法:"
    echo "  $0 init       <set_id> <ws_start> <ws_end>   # 首次建 Zone"
    echo "  $0 add        <set_id> <ws_start> <ws_end>   # 新增 World"
    echo "  $0 remove     <set_id>                        # 合併移除（依 fake_worlds）"
    echo "  $0 auto       <set_id> <ws_start> <ws_end>   # 自動判斷 init 或 add"
    echo ""
    echo "  MRTG_BASE: ${MRTG_BASE}"
    exit 1
}

[[ $# -lt 2 ]] && usage

ACTION="$1"
SET_ID="$2"
WS_START="${3:-}"
WS_END="${4:-}"
SET_DIR="${MRTG_BASE}/set${SET_ID}"
CFG_FILE="monitor_s${SET_ID}.cfg"

echo "========================================"
echo "MRTG Manager: ${ACTION}"
echo "SET_ID: ${SET_ID}"
echo "MRTG_BASE: ${MRTG_BASE}"
echo "SET_DIR: ${SET_DIR}"
echo "Time: $(date '+%Y-%m-%d %H:%M:%S')"
echo "========================================"

case "${ACTION}" in
    init)
        [[ -z "$WS_START" || -z "$WS_END" ]] && { echo "ERROR: init 需要 ws_start 和 ws_end"; usage; }

        if [[ -d "$SET_DIR" ]]; then
            echo "WARNING: ${SET_DIR} 已存在，如需重建請先手動移除"
            exit 1
        fi

        echo ">>> 建立目錄 ${SET_DIR}..."
        mkdir -p "${SET_DIR}"
        cd "${SET_DIR}"

        echo ">>> 產生 header..."
        $HOME/bin/generate_mrtg_server_lists header ${SET_ID} > ${CFG_FILE}

        echo ">>> 產生 common servers..."
        $HOME/bin/generate_mrtg_server_lists common ${SET_ID} >> ${CFG_FILE}

        echo ">>> 產生 world servers (WS${WS_START} ~ WS${WS_END})..."
        $HOME/bin/generate_mrtg_server_lists world ${WS_START} ${WS_END} >> ${CFG_FILE}

        echo ">>> fix_mrtg_info..."
        _run_fix_mrtg_info ${SET_ID} ${CFG_FILE} || exit 1

        echo ">>> init 完成"
        ;;

    add)
        [[ -z "$WS_START" || -z "$WS_END" ]] && { echo "ERROR: add 需要 ws_start 和 ws_end"; usage; }

        if [[ ! -d "$SET_DIR" ]]; then
            echo "ERROR: ${SET_DIR} 不存在，請先用 init 建立"
            exit 1
        fi

        cd "${SET_DIR}"

        echo ">>> 新增 world servers (WS${WS_START} ~ WS${WS_END})..."
        $HOME/bin/generate_mrtg_server_lists world ${WS_START} ${WS_END} >> ${CFG_FILE}

        echo ">>> fix_mrtg_info..."
        _run_fix_mrtg_info ${SET_ID} ${CFG_FILE} || exit 1

        echo ">>> add 完成"
        ;;

    remove)
        if [[ ! -d "$SET_DIR" ]]; then
            echo "ERROR: ${SET_DIR} 不存在"
            exit 1
        fi

        cd "${SET_DIR}"

        echo ">>> 查詢 fake_worlds for SET_ID=${SET_ID}..."
        DELETE_WORLD_ID_LISTS=$(psql -U postgres WebTool -Atqc "SELECT id FROM fake_worlds WHERE id/100=${SET_ID} ORDER BY id" | tr '\n' ' ')

        if [[ -z "$DELETE_WORLD_ID_LISTS" ]]; then
            echo "  No fake_worlds found for SET_ID=${SET_ID}, skip"
            exit 0
        fi

        echo "  DELETE_WORLD_ID_LISTS: ${DELETE_WORLD_ID_LISTS}"

        for cfg in $(ls monitor_s${SET_ID}*cfg 2>/dev/null); do
            echo "  remove_mrtg_config_line_for_world_id ${cfg} ${DELETE_WORLD_ID_LISTS}"
            $HOME/bin/remove_mrtg_config_line_for_world_id ${cfg} ${DELETE_WORLD_ID_LISTS}
        done

        echo ">>> indexmaker（跳過 mrtg，只更新 index.html）..."
        # Atomic write：先寫到暫存檔，成功才 mv 覆蓋 index.html
        # 防止 indexmaker 失敗時 shell `>` redirect 把 index.html 砍成 0 bytes
        INDEX_TMP="index.html.tmp.$$"
        INDEX_ERR=$(mktemp)
        if /usr/bin/indexmaker --title="MRTG Index Page SET${SET_ID}" ${CFG_FILE} > "$INDEX_TMP" 2> "$INDEX_ERR"; then
            mv "$INDEX_TMP" index.html
            if [[ -s "$INDEX_ERR" ]]; then
                echo "  WARN: indexmaker 有訊息:"
                cat "$INDEX_ERR"
            fi
            rm -f "$INDEX_ERR"
        else
            rc=$?
            echo "  ERROR: indexmaker 失敗 (rc=$rc):" >&2
            cat "$INDEX_ERR" >&2
            rm -f "$INDEX_TMP" "$INDEX_ERR"
            exit 1
        fi

        echo ">>> remove 完成"
        ;;

    auto)
        [[ -z "$WS_START" || -z "$WS_END" ]] && { echo "ERROR: auto 需要 ws_start 和 ws_end"; usage; }

        if [[ -d "$SET_DIR" ]]; then
            echo ">>> 目錄已存在，執行 add..."
            cd "${SET_DIR}"

            echo ">>> 新增 world servers (WS${WS_START} ~ WS${WS_END})..."
            $HOME/bin/generate_mrtg_server_lists world ${WS_START} ${WS_END} >> ${CFG_FILE}
        else
            echo ">>> 目錄不存在，執行 init..."
            mkdir -p "${SET_DIR}"
            cd "${SET_DIR}"

            echo ">>> 產生 header..."
            $HOME/bin/generate_mrtg_server_lists header ${SET_ID} > ${CFG_FILE}

            echo ">>> 產生 common servers..."
            $HOME/bin/generate_mrtg_server_lists common ${SET_ID} >> ${CFG_FILE}

            echo ">>> 產生 world servers (WS${WS_START} ~ WS${WS_END})..."
            $HOME/bin/generate_mrtg_server_lists world ${WS_START} ${WS_END} >> ${CFG_FILE}
        fi

        echo ">>> fix_mrtg_info..."
        _run_fix_mrtg_info ${SET_ID} ${CFG_FILE} || exit 1

        echo ">>> auto 完成"
        ;;

    *)
        echo "ERROR: unknown action '${ACTION}'"
        usage
        ;;
esac

echo ""
echo "========================================"
echo "MRTG Manager ${ACTION} 完成: $(date '+%Y-%m-%d %H:%M:%S')"
echo "========================================"
