#!/bin/sh

cleanup() {
	kill "$BLPID" 2> /dev/null
}

setup() {
	modprobe bridge 2> /dev/null
	modprobe cfg80211 2> /dev/null
	modprobe libcrc32c 2> /dev/null
	modprobe crc16 2> /dev/null
	insmod /mnt/batman-adv/net/batman-adv/batman-adv.ko

	ip link add dev bat0 type batadv
	ip link add dev bat1 type batadv

	ip link add dev veth0 type veth peer name veth1

	ip link set dev veth0 master bat0
	ip link set dev veth1 master bat1

	ip link set dev veth0 address 02:11:22:33:44:01 up
	ip link set dev veth1 address 02:11:22:33:44:02 up

	ip link set dev bat0 address 02:11:22:33:44:11 up
	ip link set dev bat1 address 02:11:22:33:44:12 up

	echo "# Waiting 30 seconds for initial BLA brodcast blocking to stop"
	sleep 30
}

teardown() {
	ip link del dev bat0
	ip link del dev bat1
	ip link del dev veth0
	#ip link del dev veth1
	rmmod batman-adv
}

run() {
	ping6 -i 5 ff02::1:ff33:4412%bat0
}

breaker_loop() {
	for i in `seq 23 4096`; do
		mausezahn bat0 -q -t ip -Q $i -a 02:33:02:34:00:01 -A 192.168.0.123 -B 255.255.255.255 -b ff:ff:ff:ff:ff:ff -p 64
		sleep 32
	done
}

run_broken() {
	trap cleanup EXIT INT

	# This loop breaks broadcast/multicast:
	breaker_loop &
	BLPID="$!"

	run
}

case "$1" in
setup)
	setup
	;;
teardown)
	teardown
	;;
restart)
	teardown
	sleep 3
	setup
	;;
run)
	echo "# Without background mausezahn ---"
	echo "# Expecting continuous ICMPv6 Echo replies"
	run
	;;
run_broken)
	echo "# With background mausezahn ---"
	echo "# Expecting continuous ICMPv6 Echo replies"
	run_broken
	;;
esac
