#!/usr/bin/env bash
# clean_n1_zone
#
# 清除指定 Zone 在 ~/bin/hosts 與 ~/.ssh/known_hosts 中的所有紀錄。
# known_hosts 清除範圍包含所有 IP 與 alias（GDS/MS/GAMEDB/SOCIETYS/SOCIETYDB/RANKS/CHATS/WS/WHS/WORLDDB/WWEBSPS 等）。
#
# 用法:
#   clean_n1_zone <Zone ID>
#
# 範例:
#   clean_n1_zone 0     # 全砍（AccountDB + 所有 GameDB/WorldDB + Zone 註解）
#   clean_n1_zone 1     # 只清 AccountDB 行
#   clean_n1_zone 11    # 清除 Zone 11（by Set）

usage() {
    cat <<EOF
用法: $(basename "$0") <Zone ID>

  0        全砍（AccountDB + 所有 GameDB/WorldDB + Zone 註解，保留 TEMPLATE/CTRL）
  1        只清 AccountDB 行
  10+      清除指定 Zone（by Set）

範例:
  $(basename "$0") 0
  $(basename "$0") 1
  $(basename "$0") 11
EOF
    exit 1
}

[[ $# -ne 1 ]] && usage

ZONE_ID="$1"

# 參數驗證：只接受 0, 1, 或 10 以上的數字
if ! [[ "$ZONE_ID" =~ ^[0-9]+$ ]]; then
    echo "錯誤：Zone ID 必須是數字，收到 '${ZONE_ID}'"
    echo ""
    usage
fi
if [[ "$ZONE_ID" -ge 2 && "$ZONE_ID" -le 9 ]]; then
    echo "錯誤：Zone ID ${ZONE_ID} 不合法（合法值：0, 1, 10+）"
    echo ""
    usage
fi

HOSTS_FILE="$HOME/bin/hosts"
KNOWN_HOSTS="$HOME/.ssh/known_hosts"
TMPFILE=$(mktemp)

if [[ "$ZONE_ID" == "0" ]]; then
    # ── Zone 0: 全砍（AccountDB + 所有 GameDB/WorldDB + Zone 註解）────────────
    echo "======================================================"
    echo " clean_n1_zone Zone ID: 0 (全砍)"
    echo " 保留: TEMPLATE, CTRL, header/footer 註解"
    echo "======================================================"

    echo ""
    echo "[Step 1] 清除 ${HOSTS_FILE} 中所有遊戲伺服器行與 Zone 註解..."

    if [[ ! -f "$HOSTS_FILE" ]]; then
        echo "  找不到 ${HOSTS_FILE}，略過"
    else
        python3 - "$HOSTS_FILE" "$TMPFILE" <<'PYEOF'
import sys

hosts_file = sys.argv[1]
tmpfile    = sys.argv[2]

KEEP_ALIASES = {"TEMPLATE", "CTRL"}
HEADER_MARK = "DO NOT CHANGE THE SERVER NAMES BELOW"
FOOTER_MARK = "DO NOT CHANGE THE SERVER NAMES ABOVE"

lines = open(hosts_file).read().splitlines()
new_lines = []
removed = 0
targets = []
in_block = False  # 是否在 header~footer 區塊內

for line in lines:
    stripped = line.strip()

    # 偵測區塊邊界
    if HEADER_MARK in stripped:
        in_block = True
        new_lines.append(line)
        continue
    if FOOTER_MARK in stripped:
        in_block = False
        new_lines.append(line)
        continue

    # 區塊外：一律不動
    if not in_block:
        new_lines.append(line)
        continue

    # ── 以下為區塊內的處理 ──

    # 空行保留
    if not stripped:
        new_lines.append(line)
        continue

    # Zone 註解（## ）砍掉，其他註解保留
    if stripped.startswith("#"):
        if stripped.startswith("## "):
            print(f"  [刪除] {line}")
            removed += 1
        else:
            new_lines.append(line)
        continue

    # 資料行：含 TEMPLATE 或 CTRL 保留，其餘砍
    parts = stripped.split()
    aliases = set(parts[1:]) if len(parts) > 1 else set()

    if aliases & KEEP_ALIASES:
        new_lines.append(line)
        continue

    print(f"  [刪除] {line}")
    removed += 1
    for token in parts:
        targets.append(token)
        lower = token.lower()
        if lower != token:
            targets.append(lower)

output = "\n".join(new_lines)
if not output.endswith("\n"):
    output += "\n"
open(hosts_file, "w").write(output)
print(f"  完成，共刪除 {removed} 行")

with open(tmpfile, "w") as f:
    for t in targets:
        f.write(t + "\n")
PYEOF
    fi

elif [[ "$ZONE_ID" == "1" ]]; then
    # ── Zone 1: 只清除 AccountDB 行 ──────────────────────────────────────────
    echo "======================================================"
    echo " clean_n1_zone Zone ID: 1 (AccountDB only)"
    echo " 匹配關鍵字: ACCOUNTDB"
    echo "======================================================"

    echo ""
    echo "[Step 1] 清除 ${HOSTS_FILE} 中含 ACCOUNTDB 的行，並收集所有 IP & alias..."

    if [[ ! -f "$HOSTS_FILE" ]]; then
        echo "  找不到 ${HOSTS_FILE}，略過"
    else
        python3 - "$HOSTS_FILE" "$TMPFILE" <<'PYEOF'
import sys

hosts_file = sys.argv[1]
tmpfile    = sys.argv[2]

lines = open(hosts_file).read().splitlines()
new_lines = []
removed = 0
targets = []

for line in lines:
    stripped = line.strip()
    if not stripped or stripped.startswith("#"):
        new_lines.append(line)
        continue

    parts = stripped.split()
    if "ACCOUNTDB" in parts:
        print(f"  [刪除] {line}")
        removed += 1
        for token in parts:
            targets.append(token)
            lower = token.lower()
            if lower != token:
                targets.append(lower)
        continue

    new_lines.append(line)

output = "\n".join(new_lines)
if not output.endswith("\n"):
    output += "\n"
open(hosts_file, "w").write(output)
print(f"  完成，共刪除 {removed} 行")

with open(tmpfile, "w") as f:
    for t in targets:
        f.write(t + "\n")
PYEOF
    fi

else
    # ── Zone 10+: 清除指定 Zone 的 MS/WS 行 ──────────────────────────────────
    SUBNET_INDEX=$(( (ZONE_ID - 10) / 15 ))
    SUBNET_THIRD=$(( 10 + SUBNET_INDEX ))
    OFFSET=$(( ZONE_ID - SUBNET_INDEX * 15 ))
    MS_IP="10.150.${SUBNET_THIRD}.${OFFSET}"
    WS_IP_INIT_LAST=$(( OFFSET * 10 + 1 ))
    WS_IP_PREFIX="10.150.${SUBNET_THIRD}"

    echo "======================================================"
    echo " clean_n1_zone Zone ID: ${ZONE_ID}"
    echo " MS IP:        ${MS_IP}"
    echo " WS IP 範圍:   ${WS_IP_PREFIX}.${WS_IP_INIT_LAST} ~ ${WS_IP_PREFIX}.$((WS_IP_INIT_LAST + 9))"
    echo "======================================================"

    echo ""
    echo "[Step 1] 清除 ${HOSTS_FILE}，並收集所有 IP & alias..."

    if [[ ! -f "$HOSTS_FILE" ]]; then
        echo "  找不到 ${HOSTS_FILE}，略過"
    else
        python3 - "$HOSTS_FILE" "$ZONE_ID" "$MS_IP" "$WS_IP_PREFIX" "$WS_IP_INIT_LAST" "$TMPFILE" <<'PYEOF'
import sys, re

hosts_file   = sys.argv[1]
zone_id      = int(sys.argv[2])
ms_ip        = sys.argv[3]
ws_prefix    = sys.argv[4]
ws_last_init = int(sys.argv[5])
tmpfile      = sys.argv[6]
ws_ips       = {f"{ws_prefix}.{ws_last_init + i}" for i in range(10)}

lines = open(hosts_file).read().splitlines()
new_lines = []
removed = 0
targets = []

for line in lines:
    stripped = line.strip()

    if not stripped or stripped.startswith("#"):
        if re.search(rf"\bS{zone_id}\b", stripped):
            print(f"  [刪除] {line}")
            removed += 1
            continue
        new_lines.append(line)
        continue

    parts = stripped.split()
    ip = parts[0]

    if ip == ms_ip or ip in ws_ips:
        print(f"  [刪除] {line}")
        removed += 1
        for token in parts:
            targets.append(token)
            lower = token.lower()
            if lower != token:
                targets.append(lower)
        continue

    new_lines.append(line)

output = "\n".join(new_lines)
if not output.endswith("\n"):
    output += "\n"
open(hosts_file, "w").write(output)
print(f"  完成，共刪除 {removed} 行")

with open(tmpfile, "w") as f:
    for t in targets:
        f.write(t + "\n")
PYEOF
    fi
fi

# ── Step 2: 清除 ~/.ssh/known_hosts（所有 IP & alias）────────────────────────
echo ""
echo "[Step 2] 清除 ${KNOWN_HOSTS}（IP & 所有 alias）..."

if [[ ! -f "$KNOWN_HOSTS" ]]; then
    echo "  找不到 ${KNOWN_HOSTS}，略過"
elif [[ ! -s "$TMPFILE" ]]; then
    echo "  無收集到任何 target，略過"
else
    REMOVED=0
    while IFS= read -r target; do
        [[ -z "$target" ]] && continue
        result=$(ssh-keygen -f "$KNOWN_HOSTS" -R "$target" 2>&1)
        if echo "$result" | grep -q "updated"; then
            echo "  [刪除] $target"
            (( REMOVED++ ))
        fi
    done < "$TMPFILE"
    echo "  完成，共清除 ${REMOVED} 筆"
fi

rm -f "$TMPFILE"

echo ""
echo "======================================================"
echo " Zone ${ZONE_ID} 清除完成"
echo "======================================================"
