#!/bin/sh

set -e

add_ns() {
	ip netns add $1
	ns $1 sysctl -w net.ipv6.conf.all.accept_dad=0 >/dev/null
	ns $1 sysctl -w net.ipv6.conf.default.accept_dad=0 >/dev/null
}

del_ns() {
	ip netns del $1
}

add_link() {
	ip link add "veth$1$2" type veth peer name "veth$2$1"
	ip link set mtu $3 dev "veth$1$2"
	ip link set mtu $3 dev "veth$2$1"
	ip link set netns $1 dev "veth$1$2" 
	ip link set netns $2 dev "veth$2$1"
	ns $1 ip link set up dev "veth$1$2"
	ns $2 ip link set up dev "veth$2$1"
}

add_ip() {
	ns $1 ip addr add $2 dev $3
}

do_route() {
	ns $1 ip route $2 $3 via $4
}

add_route() {
	do_route $1 add $2 $3
}

del_route() {
	do_route $1 del $2 $3
}

add_route_sadr() {
	ns $1 ip route add $2 from $4 via $3
}

ns() {
	local n=$1
	shift
	ip netns exec $n "$@"
}

test_ping() {
	# Trigger PMTU
	ns a ping -c 1 -s 2000 fd01::c >/dev/null|| true

	# Test ping
	if ns a ping -c 1 -s 2000 fd01::c >/dev/null; then
		echo "$1SUCCESS"
	else
		echo "$1FAIL"
	fi
}

del_ns a || true
del_ns b || true
del_ns c || true

add_ns a
add_ns b
add_ns c

ns b sysctl -w net.ipv6.conf.all.forwarding=1 >/dev/null

add_link a b 1500
add_link b c 1280

add_ip a fd00::a/64 vethab
add_ip b fd00::b/64 vethba
add_ip b fd01::b/64 vethbc
add_ip c fd01::c/64 vethcb

add_route c fd00::/64 fd01::b

#add_route a fd00::/8 fd00::b
#test_ping "No SADR: "
#del_route a fd00::/8 fd00::b

add_route_sadr a fd00::/8 fd00::b fd00::/64
test_ping "SADR:    "

