#!/bin/bash

# Usage: ./pve-bulkaddinterface.sh <vmid> <vmbridge> <vlan-start> <vlan-end> <quantity>

if [[ $# -ne 5 ]]; then
    echo "Usage: $0 <vmid> <vmbridge> <vlan-start> <vlan-end> <quantity>"
    exit 1
fi

vmid="$1"
vmbridge="$2"
vlan_start="$3"
vlan_end="$4"
quantity="$5"

# Validate input
if ! [[ "$vmid" =~ ^[0-9]+$ && "$vlan_start" =~ ^[0-9]+$ && "$vlan_end" =~ ^[0-9]+$ && "$quantity" =~ ^[0-9]+$ ]]; then
    echo "❌ Error: All inputs must be numeric."
    exit 1
fi

# Generate VLANs
vlans=($(seq "$vlan_start" "$vlan_end"))

if [[ "${#vlans[@]}" -lt "$quantity" ]]; then
    echo "❌ Error: VLAN range too small for requested quantity ($quantity)."
    exit 1
fi

# Get existing netX
used_nets=$(qm config "$vmid" | grep -E '^net[0-9]+:' | cut -d: -f1 | sed 's/net//')
echo "✅ Adding $quantity interfaces to VM $vmid on bridge $vmbridge using VLANs ${vlans[*]:0:$quantity}"

added=0
for ((i = 1; i <= 31; i++)); do
    if echo "$used_nets" | grep -qw "$i"; then
        continue
    fi

    vlan="${vlans[$added]}"
    echo "➕ Adding net$i: virtio,bridge=$vmbridge,tag=$vlan"
    qm set "$vmid" -net$i "virtio,bridge=$vmbridge,tag=$vlan"

    echo "🌐 Setting ipconfig$i to DHCP"
    qm set "$vmid" -ipconfig$i "ip=dhcp"

    added=$((added + 1))
    if [[ "$added" -ge "$quantity" ]]; then
        break
    fi
done

if [[ "$added" -lt "$quantity" ]]; then
    echo "⚠️ Warning: Only $added interfaces were added due to existing configuration."
fi
