#!/bin/sh

set -e

. ./helpers

ME=$(basename $0)

setup_sandbox

FRR_LEAF1=${SANDBOX}/out/leaf1/etc/frr/frr.conf

# Every leaf originates the cluster management subnets into BGP: a
# blackhole static (so the "network" statement finds a RIB match) plus
# the network statement itself, inside the ipv4 address-family.
run_setup start
assert_eq "ikvswitch-setup start rc" "${SETUP_RC}" "0"
for mgmt in 192.168.101.0/24 192.168.121.0/26 192.168.122.0/26 192.168.123.0/26 ; do
	assert_file_contains "leaf1 blackhole ${mgmt}" "${FRR_LEAF1}" "ip route ${mgmt} blackhole"
	assert_file_contains "leaf1 network ${mgmt}" "${FRR_LEAF1}" "network ${mgmt}"
done

# The blackhole statics must be written before the "router bgp" block:
# bgpd stops reading frr.conf when it finds, inside the BGP context, a
# command it doesn't own (ip route belongs to staticd), which drops
# everything that follows, including the address-families needed to
# peer with the spines at all.
FIRST_STATIC=$(grep -n "^ip route 192.168.101.0/24 blackhole" ${FRR_LEAF1} | cut -d: -f1)
FIRST_BGP=$(grep -n "^router bgp " ${FRR_LEAF1} | cut -d: -f1)
if [ -z "${FIRST_STATIC}" ] || [ -z "${FIRST_BGP}" ] ; then
	echo "test_mgmt_subnets: missing static or bgp block in ${FRR_LEAF1}"
	exit 1
fi
LAST_STATIC=$(grep -n "^ip route .* blackhole" ${FRR_LEAF1} | tail -1 | cut -d: -f1)
if [ "${LAST_STATIC}" -ge "${FIRST_BGP}" ] ; then
	echo "test_mgmt_subnets: a blackhole static sits inside the router bgp block (static at line ${LAST_STATIC}, bgp at line ${FIRST_BGP})"
	exit 1
fi

# The address-family activation must be present: the spine peer-group
# is activated in both families, which is what was lost when the
# statics sat inside the BGP block.
assert_file_contains "leaf1 ipv4 AF" "${FRR_LEAF1}" "address-family ipv4 unicast"
assert_file_contains "leaf1 ipv6 AF" "${FRR_LEAF1}" "address-family ipv6 unicast"
assert_file_contains "leaf1 spine activate" "${FRR_LEAF1}" "neighbor spine activate"
assert_file_contains "leaf1 redistribute static" "${FRR_LEAF1}" "redistribute static route-map map-redistribute"

# A configuration file predating CLUSTER_MGMT_SUBNETS must generate a
# valid config with no static and no network statement, rather than
# malformed empty-value lines.
sed -i -e '/^CLUSTER_MGMT_SUBNETS=/d' ${SANDBOX}/etc/ikvswitch.conf
run_setup start
assert_eq "start without CLUSTER_MGMT_SUBNETS rc" "${SETUP_RC}" "0"
assert_file_not_contains "leaf1 no blackhole" "${FRR_LEAF1}" "blackhole"
assert_file_not_contains "leaf1 no network" "${FRR_LEAF1}" "network 192.168"

exit 0
