#!/bin/sh
# Factory default:
#  1) all switch ports in VLAN 1 of br0
#  2) no switch ports => DHCP on eth0
#  3) no eth0

create_bridge()
{
    nm=$1
    shift
    ports=$@

    touch "/etc/network/interfaces.d/$nm"
    for port in $ports; do
	cat <<-EOF >>"/etc/network/interfaces.d/$nm"
		iface $port
		    bridge-access 1
		    post-up ip link set $port group port
		EOF
    done
    cat <<-EOF >> "/etc/network/interfaces.d/$nm"

	auto $nm
	iface $nm
	    bridge-ports $ports
	    bridge-vlan-aware yes
	    bridge-stp on
	    bridge-vids 1

	auto vlan1
	iface vlan1 inet dhcp
	    vlan-id 1
	    vlan-raw-device $nm
	    post-up ip link set vlan1 group iface
	EOF
    ip link set vlan1 group iface
}

# Check if already set up
[ -z "$(ls -A /etc/network/interfaces.d/)" ] || exit 0

# Check for custom hostname from Qemu/Qeneth
nm=$(cat /sys/firmware/qemu_fw_cfg/by_name/opt/hostname/raw)
if [ -n "$nm" ]; then
    hostnm "$nm"
fi

# need to check for 'length > 0' because ip command
# outputs empty json objects for non-port group ifs
ports=$(ip -json link show group port | jq -r '.[].ifname | select(length > 0)' | tr "\n" " ")
if [ -n "$ports" ]; then
    create_bridge br0 $ports
else
    ifaces=$(ip -json addr show  |jq -r '.[] | select(.link_type=="ether").ifname')
    for iface in $ifaces; do
	cat  <<-EOF > "/etc/network/interfaces.d/$iface"
		auto $iface
		iface $iface inet dhcp
		    pre-up ip link set $iface group iface
		EOF
    done
fi
