#!/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

# Sometimes the sysfs is not populated when the switch driver is loaded, with the result
# that the DSA interface was not found (no /dsa/tagging entry in sysfs. See issue #685.
#
# This mitigates that problem by waiting for sysfs to come up if a DSA switch is found
if [ -n "$(devlink -j dev info | jq -r '.info.[].driver' | grep -q mv88e6085)" ]; then
	timeout=50
	while [ -z "$(ls /sys/class/net/*/dsa/tagging)" ]; do
		timeout=$((timeout-1))
		if [ $timeout -eq 0 ]; then
			logger -k -p user.emerg -t "$ident" "Failed to find DSA interface"
			exit 1
		fi
		sleep 0.1
	done

	logger -k -p user.notice -t "$ident" "Found DSA interface in $timeout seconds"
fi

# 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
	ip link set "$iface" group port
done

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