#!/bin/sh
# Find any switch ports, classify and rename to Infix std
#

ident=$(basename "$0")
num=0

# Perform any interface renames as dictated by, first, any Qemu
# override (for testing), and then the user specific /etc/mactab
for file in /sys/firmware/qemu_fw_cfg/by_name/opt/mactab/raw /etc/mactab; do
	if [ -f $file ]; then
		logger -k -p user.notice -t "$ident" "calling nameif -c $file"
		nameif -c $file -s
	fi
done

# Find CPU interfaces used for connecting to a switch managed by DSA
for netif in /sys/class/net/*; do
	iface=$(basename "$netif")
	[ -f "/sys/class/net/$iface/dsa/tagging" ] || continue

	# Disable SLAAC frames and such, that's for the port interfaces, and
	# bring it up so we get link events from the ports to the bridge.
	sysctl -q "net.ipv6.conf.$iface.disable_ipv6=1"

	dsa="dsa$num"
	logger -k -p user.notice -t "$ident" "Found DSA interface, renaming $iface -> $dsa"
	ip link set dev "$iface" name $dsa group internal
	num=$((num + 1))
done

# Find and mark all switch ports
ports=$(devlink -j port | jq -r '.port[]
				 | select(.flavour == "physical")
				 | .netdev')
for iface in $ports; do
	# On systems with multiple switch trees, a port may be _both_
	# a physical port, registered with devlink, _and_ a DSA
	# port. In those cases, hold on to our initial "internal"
	# classification.
	[ $(ip -j link show dev "$iface" | jq -r '.[0].group') = internal ] && continue

	ip link set "$iface" group port
done

# At least loopback in iface group
ip link set lo group iface
