#!/bin/sh
# Verify that mstpd manages a Linux bridge end-to-end via mstpctl

set -eu

BR=mstpd-test-br
PORT=mstpd-test-dum
MSTPD_PID=
PID_FILE=/var/run/mstpd.pid

cleanup() {
    [ -n "$MSTPD_PID" ] && kill "$MSTPD_PID" 2>/dev/null || true
    ip link del "$BR" 2>/dev/null || true
    ip link del "$PORT" 2>/dev/null || true
}
trap cleanup EXIT

# Start mstpd and wait for it to write its PID file after daemonising
mstpd
i=0
until [ -s $PID_FILE ]; do
    [ $i -lt 50 ] || {
        echo "timed out waiting for mstpd PID file" >&2
        exit 1
    }
    sleep 0.1
    i=$((i + 1))
done
MSTPD_PID=$(cat $PID_FILE)
[ -n "$MSTPD_PID" ]

ip link add name "$BR" type bridge
ip link add name "$PORT" type dummy
ip link set "$PORT" master "$BR"
ip link set "$PORT" up
ip link set "$BR" up

# Hand the bridge to mstpd. This is what /sbin/bridge-stp would do in
# non-container environment
mstpctl addbridge "$BR"

mstpctl showbridge "$BR"
mstpctl showport "$BR" "$PORT"
mstpctl showtree "$BR" 0

# Reconfigure and verify the daemon still tracks the bridge
mstpctl setforcevers "$BR" rstp
mstpctl settreeprio "$BR" 0 8
mstpctl showbridge "$BR" >/dev/null

mstpctl delbridge "$BR"
