#!/usr/bin/env bash
# ==============================================================================
# /usr/local/bin/setup-proxmox.sh
# Homelab Proxmox VE Dual-Bridge Network Installer
# ==============================================================================
set -euo pipefail

if [ "$EUID" -ne 0 ]; then
    echo "❌ Error: This script must be run as root on Proxmox VE (use sudo bash $0)" >&2
    exit 1
fi

PHYS_NIC="${1:-eno1}"
PVE_TRANSIT_IP="${2:-172.16.100.2}"
T490_TRANSIT_IP="${3:-172.16.100.1}"
VM_GATEWAY_IP="192.168.45.1"

echo "======================================================================"
echo "Homelab Proxmox VE Dual-Bridge Network Setup"
echo "Physical Interface:   ${PHYS_NIC}"
echo "Transit Management:   ${PVE_TRANSIT_IP}/24 (Gateway: ${T490_TRANSIT_IP})"
echo "Internal Workloads:   ${VM_GATEWAY_IP}/24 (vmbr1 - isolated software bridge)"
echo "======================================================================"

# Step 1: Backup existing interfaces
BACKUP_PATH="/etc/network/interfaces.bak.$(date +%s)"
echo "==> [1/4] Backing up current /etc/network/interfaces to ${BACKUP_PATH}..."
cp /etc/network/interfaces "${BACKUP_PATH}"

# Step 2: Configure dual bridges in /etc/network/interfaces
echo "==> [2/4] Writing dual-bridge network interfaces..."
cat << EOF > /etc/network/interfaces
auto lo
iface lo inet loopback

iface ${PHYS_NIC} inet manual

auto vmbr0
iface vmbr0 inet static
	address ${PVE_TRANSIT_IP}/24
	gateway ${T490_TRANSIT_IP}
	bridge-ports ${PHYS_NIC}
	bridge-stp off
	bridge-fd 0
	dns-nameservers 1.1.1.1 9.9.9.9

auto vmbr1
iface vmbr1 inet static
	address ${VM_GATEWAY_IP}/24
	bridge-ports none
	bridge-stp off
	bridge-fd 0
EOF

# Step 3: Enable Kernel IP Forwarding
echo "==> [3/4] Enabling IPv4 kernel forwarding for pure L3 routing..."
cat << EOF > /etc/sysctl.d/99-pve-routing.conf
net.ipv4.ip_forward = 1
net.ipv6.conf.all.forwarding = 0
net.ipv4.conf.all.send_redirects = 0
net.ipv4.conf.vmbr0.send_redirects = 0
net.ipv4.conf.vmbr1.send_redirects = 0
EOF
sysctl -p /etc/sysctl.d/99-pve-routing.conf

# Step 4: Reload networking
echo "==> [4/4] Applying network configuration..."
if command -v ifreload >/dev/null 2>&1; then
    ifreload -a
else
    systemctl restart networking
fi

echo "======================================================================"
echo "✅ Proxmox VE network configuration applied successfully!"
echo "   Management Web GUI: https://${PVE_TRANSIT_IP}:8006"
echo "   Internal Workload Gateway: ${VM_GATEWAY_IP}"
echo "======================================================================"
