#!/usr/bin/env bash
# clean_n1_zone
#
# 清除指定 Zone 在 ~/bin/hosts 與 ~/.ssh/known_hosts 中的所有紀錄。
#
# 用法:
#   clean_n1_zone <Zone ID>
#
# 範例:
#   clean_n1_zone 11

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

  Zone ID  要清除的 Zone ID，e.g. 11

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

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

ZONE_ID="$1"
HOSTS_FILE="$HOME/bin/hosts"
KNOWN_HOSTS="$HOME/.ssh/known_hosts"

# ── 推斷 IP 範圍 ──────────────────────────────────────────────────────────────
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 "======================================================"

# ── Step 1: 清除 ~/bin/hosts ──────────────────────────────────────────────────
echo ""
echo "[Step 1] 清除 ${HOSTS_FILE}..."

if [[ ! -f "$HOSTS_FILE" ]]; then
    echo "  找不到 ${HOSTS_FILE}，略過"
else
    python3 - "$HOSTS_FILE" "$ZONE_ID" "$MS_IP" "$WS_IP_PREFIX" "$WS_IP_INIT_LAST" <<'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])
ws_ips       = {f"{ws_prefix}.{ws_last_init + i}" for i in range(10)}

lines = open(hosts_file).read().splitlines()
new_lines = []
removed = 0
i = 0
while i < len(lines):
    line = lines[i]
    stripped = line.strip()

    # 跳過空行與純 comment，但保留
    if not stripped or stripped.startswith("#"):
        # 檢查是否為 Zone comment（## ... S{zone_id} 或 ## ... (S{zone_id})）
        if re.search(rf"\bS{zone_id}\b", stripped):
            print(f"  [刪除] {line}")
            removed += 1
            i += 1
            continue
        new_lines.append(line)
        i += 1
        continue

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

    # MS IP 行
    if ip == ms_ip:
        print(f"  [刪除] {line}")
        removed += 1
        i += 1
        continue

    # WS IP 行
    if ip in ws_ips:
        print(f"  [刪除] {line}")
        removed += 1
        i += 1
        continue

    new_lines.append(line)
    i += 1

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

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

if [[ ! -f "$KNOWN_HOSTS" ]]; then
    echo "  找不到 ${KNOWN_HOSTS}，略過"
else
    ssh-keygen -f "$KNOWN_HOSTS" -R "$MS_IP" 2>/dev/null && echo "  [刪除] $MS_IP" || echo "  [不存在] $MS_IP"
    for i in $(seq 0 9); do
        ip="${WS_IP_PREFIX}.$((WS_IP_INIT_LAST + i))"
        ssh-keygen -f "$KNOWN_HOSTS" -R "$ip" 2>/dev/null && echo "  [刪除] $ip" || echo "  [不存在] $ip"
    done
fi

# ── Step 3: 清除 ~/.ssh/known_hosts（Hostname）───────────────────────────────
echo ""
echo "[Step 3] 清除 ${KNOWN_HOSTS}（Hostname）..."

if [[ ! -f "$KNOWN_HOSTS" ]]; then
    echo "  找不到 ${KNOWN_HOSTS}，略過"
else
    ssh-keygen -f "$KNOWN_HOSTS" -R "gamedb${ZONE_ID}" 2>/dev/null && echo "  [刪除] gamedb${ZONE_ID}" || echo "  [不存在] gamedb${ZONE_ID}"
    for i in $(seq 1 10); do
        hostname="worlddb${ZONE_ID}$(printf '%02d' $i)"
        ssh-keygen -f "$KNOWN_HOSTS" -R "$hostname" 2>/dev/null && echo "  [刪除] $hostname" || echo "  [不存在] $hostname"
    done
fi

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