#!/bin/sh

# Create network namespaces
ip netns add ca
ip netns add cb
ip netns exec ca ip link set lo up
ip netns exec cb ip link set lo up

# Link between them
ip netns exec ca ip link add name xxx type veth peer name xxx netns cb
ip netns exec ca ip link set xxx up
ip netns exec cb ip link set xxx up
ip netns exec ca ip a add 10.0.0.1/24 dev xxx
ip netns exec cb ip a add 10.0.0.2/24 dev xxx

# Test a ping
ip netns exec ca ping -c 1 10.0.0.2

# Create configs
cat >ca.conf <<EOF
log "ca.log" all;
debug protocols all;

router id 10.0.0.1;

protocol direct {
	interface "yyy";
}

protocol device {}

protocol static testproto {
	route 10.20.0.0/16 via 10.0.10.10;
}

protocol static testproto2 {
	route 10.30.0.0/16 via 10.0.10.10;
}

function export_filter() {
	if proto = "testproto" then {
		return true;
	}

	if proto = "testproto2" then {
		return true;
	}

	return false;
}

protocol bgp testbgp {
	local 10.0.0.1 as 65533;
	neighbor 10.0.0.2 as 65533;
	start delay time 1;
	export where export_filter();
}
EOF

cat >cb.conf <<EOF
log "cb.log" all;
debug protocols all;

router id 10.0.0.2;

protocol device {}

protocol bgp {
  export all;
  neighbor 10.0.0.1 as 65533;
  local 10.0.0.2 as 65533;
}
EOF

# Run BIRD
ip netns exec ca bird -c ca.conf -s ca.sock
ip netns exec cb bird -c cb.conf -s cb.sock

# Dummy link on ca
ip netns exec ca ip link add yyy type dummy
ip netns exec ca ip link set yyy up
ip netns exec ca ip a add 10.0.10.20/24 dev yyy

showroute() {
  # Show route on ca
  echo "Routes on CA"
  sudo ip netns exec ca birdc -s ca.sock show route

  # Show route on cb
  echo "Routes on CB"
  sudo ip netns exec cb birdc -s cb.sock show route
}

echo "Show routes before reconfig"
showroute

# Reconfigure
cat >ca.conf <<EOF
log "ca.log" all;
debug protocols all;

router id 10.0.0.1;

protocol device {}

protocol direct {
	interface "yyy";
}

protocol static testproto {
	route 10.20.0.0/16 via 10.0.10.10;
}

protocol static testproto2 {
	route 10.30.0.0/16 via 10.0.10.10;
}

function export_filter() {
	if proto = "testproto" then {
		return true;
	}

	return false;
}

protocol bgp testbgp {
	local 10.0.0.1 as 65533;
	neighbor 10.0.0.2 as 65533;
	start delay time 1;
	export where export_filter();
}
EOF

birdc -s ca.sock configure soft

# Does it withdraw?
sleep 5 # wait 5 seconds, for good measure
echo "Show routes after reconfig"
showroute

# Cleanup
birdc -s ca.sock down
birdc -s cb.sock down

ip netns del ca
ip netns del cb

