#!/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 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"
TMPFILE=$(mktemp)

# ── 推斷 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 收集所有 IP & alias，並清除對應行 ──────────────────
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 = []  # 收集所有要清除的 IP & alias

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
        # 收集 IP + 所有 alias
        for token in parts:
            targets.append(token)
        continue

    new_lines.append(line)

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

# 寫出待清除的 targets
with open(tmpfile, "w") as f:
    for t in targets:
        f.write(t + "\n")
PYEOF
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 "======================================================"
