#!/bin/bash
# AWOOOI Hosts White-list Wrapper (ADR-090)
# 建立時間: 2026-04-18 台北時區
# 建立者: ogt + Claude Opus 4.7 (1M)
#
# 目的: 取代「AI 有全域 /etc/hosts sudo 權限」的安全破口
#       只允許預定義白名單主機名被寫入,且 idempotent 不重複
#
# 安裝位置: /usr/local/bin/awoooi-hosts-add
# 安裝權限: root:root 0755
# 呼叫方式 (需搭配 sudoers): sudo /usr/local/bin/awoooi-hosts-add <IP> <HOSTNAME>
#
# 例: sudo /usr/local/bin/awoooi-hosts-add 114.32.151.246 mo.wooo.work

set -euo pipefail

# ─── 白名單 ───────────────────────────────────────────────────────────────
# 新增主機名到這裡,需統帥審查並 git commit
ALLOWED_HOSTS=(
    "mo.wooo.work"
    "aiops.wooo.work"
    "bitan.wooo.work"
    "stock.wooo.work"
    "tsenyang.com"
    "www.tsenyang.com"
)

# ─── 參數驗證 ─────────────────────────────────────────────────────────────
if [[ $# -ne 2 ]]; then
    echo "Usage: $0 <IP> <HOSTNAME>" >&2
    echo "Whitelist: ${ALLOWED_HOSTS[*]}" >&2
    exit 1
fi

IP="$1"
HOST="$2"

# IP 格式驗證 (基本 IPv4)
if [[ ! "$IP" =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then
    echo "Invalid IP format: $IP" >&2
    exit 2
fi

# 主機名白名單檢查
ALLOWED=0
for allowed in "${ALLOWED_HOSTS[@]}"; do
    if [[ "$HOST" == "$allowed" ]]; then
        ALLOWED=1
        break
    fi
done

if [[ $ALLOWED -eq 0 ]]; then
    echo "Host not whitelisted: $HOST" >&2
    echo "Contact statesman to update script whitelist + git commit." >&2
    exit 3
fi

# ─── Idempotent 寫入 ──────────────────────────────────────────────────────
# 若 /etc/hosts 已有此主機名 (不限 IP),視為已設定,不重複寫
if grep -qE "^[0-9.]+[[:space:]]+${HOST}\$" /etc/hosts; then
    echo "Host $HOST already in /etc/hosts, no change."
    exit 0
fi

# 寫入 (原子 append)
echo "$IP $HOST" >> /etc/hosts
echo "Added: $IP $HOST to /etc/hosts"
