#!/bin/bash

# Usage: ./addeth.sh <vmid> <vlanid> <vmbrid> <gateway> <start_ip> <end_ip>

if [ "$#" -ne 6 ]; then
    echo "Usage: $0 <vmid> <vlanid> <vmbrid> <gateway> <start_ip> <end_ip>"
    exit 1
fi

VMID="$1"
VLANID="$2"
VMBRID="$3"
GATEWAY="$4"
START_IP="$5"
END_IP="$6"

# --- Convert IP to integer ---
ip_to_int() {
    local a b c d
    IFS=. read -r a b c d <<< "$1"
    echo $(((a << 24) + (b << 16) + (c << 8) + d))
}

# --- Convert integer to IP ---
int_to_ip() {
    local ip=$1
    echo "$(( (ip >> 24) & 255 )).$(( (ip >> 16) & 255 )).$(( (ip >> 8) & 255 )).$(( ip & 255 ))"
}

START_INT=$(ip_to_int "$START_IP")
END_INT=$(ip_to_int "$END_IP")
TOTAL_IPS=$((END_INT - START_INT + 1))

if [ "$TOTAL_IPS" -ne 13 ]; then
    echo "❌ Error: You must provide exactly 13 IPs (start to end range)."
    exit 1
fi

# --- Generate Proxmox-style MAC ---
gen_mac() {
    printf '52:54:00:%02x:%02x:%02x\n' $((RANDOM%256)) $((RANDOM%256)) $((RANDOM%256))
}

# --- Main loop ---
for i in $(seq 0 12); do
    IFACE="net${i}"
    IP_INT=$((START_INT + i))
    IP=$(int_to_ip "$IP_INT")
    MAC=$(gen_mac)

    echo "🛠 Adding $IFACE to VM $VMID with IP $IP and gateway $GATEWAY"

    # Add NIC
    qm set "$VMID" --${IFACE} "virtio=${MAC},bridge=${VMBRID},tag=${VLANID},firewall=0,rate=80"

    # Cloud-init IP config (with gateway on all interfaces)
    qm set "$VMID" --ipconfig${i} "ip=${IP}/24,gw=${GATEWAY}"
done

echo "✅ All 13 interfaces configured on VM $VMID with gateway $GATEWAY"