#!/bin/bash

# QEMU passes the TAP interface name as $1
TAP_IFACE="$1"

# Debugging: Uncomment to log outputs for debugging
# exec >> /tmp/network-down.log 2>&1
# echo "Starting network-down.sh with interface: $TAP_IFACE"

# Check if interface name was provided
if [ -z "$TAP_IFACE" ]; then
    echo "Error: No interface name provided" >&2
    exit 1
fi

# Remove TAP interface from the bridge
echo "Removing $TAP_IFACE from bridge..."
ip link set "$TAP_IFACE" nomaster 2>/dev/null || true

# Bring down TAP interface
echo "Bringing down $TAP_IFACE..."
ip link set "$TAP_IFACE" down 2>/dev/null || true

# Check if there are any other interfaces on the bridge
BRIDGE_MEMBERS=$(ip link show master br0 2>/dev/null | grep -c "master br0" || true)

# If no other interfaces are using the bridge, clean it up
if [ "$BRIDGE_MEMBERS" -eq 0 ]; then
    echo "No more interfaces on br0, cleaning up bridge..."
    
    # Bring down the bridge
    ip link set br0 down 2>/dev/null || true
    
    # Delete the bridge
    ip link delete br0 2>/dev/null || true
    
    echo "Bridge br0 removed"
fi

echo "Network cleanup completed for $TAP_IFACE"
exit 0
