#!/bin/bash
set -e
IFACE=$1


### IPv4 is IFACE public and has a route? if so, nuke it
for route in $(vtysh -c "show ip route kernel" | grep "$IFACE" | awk '{ print $2 }')
  do
    echo "removing route for $IFACE: $route"
    ip route del $route
done
#### IPv6 is IFACE public and has a route? if so, nuke it
#for route in $(vtysh -c "show ipv6 route kernel" | grep "$IFACE" | awk '{ print $2 }')
#  do
#    echo "removing route for $IFACE: $route"
#    ip route del $route
#done


### is IFACE private and has a local bridge?
BRIDGE=$(readlink -f /sys/devices/virtual/net/$IFACE/brport/bridge || true)

if [ ! -z $BRIDGE ]; then
    BRIDGE=${BRIDGE##*/}
    echo "removing $IFACE from $BRIDGE"
    brctl delif $BRIDGE $IFACE
    if ! ls /sys/devices/virtual/net/$BRIDGE/brif/ | grep -qv vxlan; then	#if so is the *local* bridge now empty? if so, nuke the whole bridge including tunnel endpoint
        echo "removing unused bridge: $BRIDGE"
	ip link del dev $(ls /sys/devices/virtual/net/$BRIDGE/brif/ | grep vxlan)
        ip link set down $BRIDGE
        brctl delbr $BRIDGE
    fi
fi