#!/bin/sh

PATH=/mnt/batctl:$PATH
NUM_NODES=8

setup() {
	modprobe crc16 > /dev/null
	modprobe libcrc32c > /dev/null
	modprobe bridge > /dev/null
	modprobe cfg80211 > /dev/null

	insmod /mnt/batman-adv/net/batman-adv/batman-adv.ko

	for i in `seq 1 $NUM_NODES`; do
		batctl meshif bat$i interface create
		ip link add dummy$i type dummy
		batctl meshif bat$i interface add dummy$i

		brctl addbr br$i
		brctl addif br$i bat$i

		ip link set up dev bat$i
		ip link set up dev dummy$i
		ip link set up dev br$i
	done

	# cabeling
	for i in `seq 1 $NUM_NODES`; do
		for j in `seq 1 $NUM_NODES`; do
			[ $i -ge $j ] && continue

			ip link add mesh-bat$i-bat$j type veth peer name mesh-bat$j-bat$i
			batctl meshif bat$i interface add mesh-bat$i-bat$j
			batctl meshif bat$j interface add mesh-bat$j-bat$i

			ip link set up dev mesh-bat$i-bat$j
			ip link set up dev mesh-bat$j-bat$i
		done
	done

	ip link add lan-br1-br0 type veth peer name lan-br0-br1
	ip link add lan-br2-br0 type veth peer name lan-br0-br2

	brctl addbr br0
	brctl addif br0 lan-br0-br1
	brctl addif br0 lan-br0-br2
	brctl addif br1 lan-br1-br0
	brctl addif br2 lan-br2-br0

	ip link set up dev lan-br0-br1
	ip link set up dev lan-br1-br0
	ip link set up dev lan-br0-br2
	ip link set up dev lan-br2-br0
	ip link set up dev br0
}

teardown() {
	brctl delif br0 lan-br0-br1
	brctl delif br0 lan-br0-br2
	brctl delif br1 lan-br1-br0
	brctl delif br2 lan-br2-br0
	ip link delete lan-br0-br1
	ip link delete lan-br0-br2
	ip link delete br0

	for i in `seq 1 $NUM_NODES`; do
		for j in `seq 1 $NUM_NODES`; do
			[ $i -ge $j ] && continue

			ip link delete mesh-bat$i-bat$j
		done

		ip link delete bat$i
		ip link delete br$i
		ip link delete dummy$i
	done

	rmmod batman-adv
}

if [ $# -ne 1 ]; then
	echo ups
	exit 1
fi

if [ "$1" = "setup" ]; then
	setup
elif [ "$1" = "teardown" ]; then
	teardown
elif [ "$1" = "reload" ]; then
	teardown
	setup
fi
