#!/bin/bash

# Ensure the script is run as root
if [ "$EUID" -ne 0 ]; then
  echo "Please run this script with sudo."
  exit 1
fi

# 1. List all bridge interfaces using 'ip link show type bridge'
# 2. Extract their interface names
# 3. Find the matching IPv4 subnet for each interface
# 4. Add the UFW allow rule

echo "Scanning for bridge network interfaces..."
bridges=$(ip -o link show type bridge | awk -F': ' '{print $2}')

if [ -z "$bridges" ]; then
    echo "No bridge networks found."
    exit 0
fi

for bridge in $bridges; do
    # Get the CIDR subnet (e.g., 172.17.0.1/16) assigned to the bridge
    subnet=$(ip -o -4 addr show dev "$bridge" | awk '{print $4}')
    
    if [ -n "$subnet" ]; then
        # Use ipcalc-like logic or python to normalize the subnet to its network address if needed,
        # but UFW natively accepts the interface CIDR notation (like 172.17.0.1/16) and adjusts it.
        echo "Found bridge $bridge with subnet $subnet"
        
        # Add the firewall rule
        ufw allow from "$subnet" to any comment "Docker bridge $bridge network"
    else
        echo "Bridge $bridge has no active IPv4 address assigned."
    fi
done

# Reload UFW to apply changes safely
ufw reload

echo "UFW rules updated successfully. Current status:"
ufw status verbose

