#!/bin/bash

set -xe

bond_mode=${1:-802.3ad}

# cleanup
dhclient -r bond0 || :
killall dnsmasq || :
ip netns del ns1 || :
ip link del bond0 || :
ip link del bond1 || :
ip link del veth0 || :
ip link del veth1 || :

# create local interfaces
ip link add bond0 type bond mode "$bond_mode"
ip link add veth0 type veth peer veth0_p
ip link add veth1 type veth peer veth1_p
ip link set veth0 master bond0
ip link set veth1 master bond0
ip link set bond0 up

# create interfaces on the other side (other netns)
ip netns add ns1
ip -n ns1 link add bond1 type bond mode "$bond_mode"
ip link set veth0_p netns ns1
ip link set veth1_p netns ns1
ip -n ns1 link set veth0_p master bond1
ip -n ns1 link set veth1_p master bond1
ip -n ns1 link set bond1 up

# add IP addresses
ip addr add 192.168.1.1/24 dev bond0
ip -n ns1 addr add 192.168.1.2/24 dev bond1
ip -n ns1 addr add 192.168.199.1/24 dev bond1

# start DHCP server
ip netns exec ns1 dnsmasq --interface=bond1 \
	--enable-ra \
	--dhcp-range="192.168.199.100,192.168.199.250,255.255.255.0,48h" \
	--dhcp-range="aa:bb:cc::100,aa:bb:cc::ffff,ra-names,slaac,64,480h" \
	--dhcp-option="option:classless-static-route,192.168.200.0/24,192.168.199.1" \
	--dhcp-option="option:dns-server,192.168.199.254" \
	--dhcp-option="option:domain-search,ipv4test.dns" \
	--dhcp-option="option6:24,aa:bb:ccd::/64,aa:bb:cc::1" \
	--dhcp-option="option6:dns-server,aa:bb:cc::254" \
	--dhcp-option="option6:domain-search,ipv6test.dns"
sleep 3

# start DHCP client
dhclient -v bond0
sleep 1

# check
ip -br a show bond0 | grep "192.168.199"

if [[ $? != 0 ]]; then
	echo DHCP failed
	exit 1
else
	echo DHCP OK
fi
