#!/bin/bash

set -e

echo "======================================================="
echo "     Proxmox VE 交互式 DHCP + NAT 一键部署脚本"
echo "======================================================="

IFACE_CFG="/etc/network/interfaces"
DNAT_FILE="/etc/pve/firewall/cluster.fw"
MAP_FILE="/etc/pve/nat-map.conf"
NAT_SCRIPT="/usr/local/bin/update-nat.sh"
DNSMASQ_CFG="/etc/dnsmasq.d/pve-nat.conf"


# -------------------------------
# 步骤 1：检查 vmbr1 是否存在
# -------------------------------
if grep -q "vmbr1" "$IFACE_CFG"; then
    echo "检测到 vmbr1 已存在，跳过创建。"
    CREATE_VMBR1="n"
else
    read -p "vmbr1 不存在，是否创建内网桥 vmbr1？(y/n) [y]: " CREATE_VMBR1
    CREATE_VMBR1=${CREATE_VMBR1:-y}
fi


if [[ "$CREATE_VMBR1" == "y" ]]; then
    echo "创建 vmbr1 网络桥..."

cat >> "$IFACE_CFG" <<EOF

auto vmbr1
iface vmbr1 inet static
    address 10.1.1.1/24

    post-up   iptables -t nat -A POSTROUTING -s '10.1.1.0/24' -o vmbr0 -j MASQUERADE
    post-down iptables -t nat -D POSTROUTING -s '10.1.1.0/24' -o vmbr0 -j MASQUERADE

EOF

    echo "vmbr1 已添加到网络配置。"
fi

# -------------------------------
# 步骤 2：输入 DHCP 起始 IP
# -------------------------------
read -p "请输入 DHCP 起始 IP（仅最后一段，例如 10，默认 10）: " DHCP_START
DHCP_START=${DHCP_START:-10}

read -p "请输入 DHCP 结束 IP（仅最后一段，例如 200，默认 200）: " DHCP_END
DHCP_END=${DHCP_END:-200}

echo "DHCP 将分配范围：10.1.1.$DHCP_START 到 10.1.1.$DHCP_END"


# -------------------------------
# 步骤 3：安装 dnsmasq DHCP
# -------------------------------
echo "安装 dnsmasq..."
apt update -y
apt install -y dnsmasq

cat > "$DNSMASQ_CFG" <<EOF
interface=vmbr1
dhcp-range=10.1.1.$DHCP_START,10.1.1.$DHCP_END,12h
dhcp-option=3,10.1.1.1
dhcp-option=6,1.1.1.1,8.8.8.8
EOF

systemctl restart dnsmasq
systemctl enable dnsmasq

echo "DHCP 已配置。"


# -------------------------------
# 步骤 4：输入自定义 NAT 映射
# -------------------------------
echo ""
echo "开始输入 NAT 映射规则（你可添加多条）"
echo "格式：内网IP 内网端口 公网端口"
echo "示例：10.1.1.10 22 1022"
echo "输入完成后按 n 停止"
echo ""

> "$MAP_FILE"

while true; do
    read -p "请输入内网 IP（例如 10.1.1.10，或 n 结束）: " IP
    [[ "$IP" == "n" ]] && break
    [[ -z "$IP" ]] && continue

    read -p "请输入内网端口（如 22）: " INPORT
    read -p "请输入公网端口（如 1022）: " OUTPORT

    echo "$IP $INPORT $OUTPORT" >> "$MAP_FILE"
    echo "添加映射：$IP:$INPORT → 公网 $OUTPORT"

    read -p "继续添加？(y/n) [y]: " MORE
    MORE=${MORE:-y}
    [[ "$MORE" == "n" ]] && break
done


# -------------------------------
# 步骤 5：生成自动 NAT 同步脚本
# -------------------------------
cat > "$NAT_SCRIPT" << 'EOF'
#!/bin/bash

MAP_FILE="/etc/pve/nat-map.conf"
CLUSTER_FW="/etc/pve/firewall/cluster.fw"

touch "$CLUSTER_FW"
touch "$MAP_FILE"

# 确保存在 [DNAT] 段
if ! grep -q "^\[DNAT\]" "$CLUSTER_FW"; then
    echo "[DNAT]" >> "$CLUSTER_FW"
fi

# 遍历映射文件并写入规则
while read -r IP INPORT OUTPORT; do
    [[ -z "$IP" ]] && continue

    RULE="rule: proto tcp dport $OUTPORT dnat to $IP:$INPORT"

    if grep -q "$RULE" "$CLUSTER_FW"; then
        continue
    fi

    echo "添加 NAT 规则：公网 $OUTPORT → $IP:$INPORT"
    echo "$RULE" >> "$CLUSTER_FW"

done < "$MAP_FILE"
EOF

chmod +x "$NAT_SCRIPT"

echo "自动 NAT 脚本已生成。"


# -------------------------------
# 步骤 6：是否启用自动同步
# -------------------------------
read -p "是否每分钟自动同步 NAT 规则？(y/n) [y]: " AUTOSYNC
AUTOSYNC=${AUTOSYNC:-y}

if [[ "$AUTOSYNC" == "y" ]]; then
    (crontab -l 2>/dev/null | grep -v update-nat.sh; echo "* * * * * /usr/local/bin/update-nat.sh >/dev/null 2>&1") | crontab -
    echo "已启用自动同步。"
else
    echo "未启用自动同步。"
fi


# -------------------------------
# 步骤 7：重启网络服务
# -------------------------------
echo "重启 networking 和 dnsmasq..."
systemctl restart networking
systemctl restart dnsmasq

echo "======================================================="
echo "      📢 安装完成！你现在可以开始使用 NAT 映射"
echo " NAT 映射文件：/etc/pve/nat-map.conf"
echo " NAT 规则查看：WebUI → Datacenter → Firewall → NAT"
echo " 自动同步脚本：/usr/local/bin/update-nat.sh"
echo "======================================================="
