#!/bin/sh

set -e

. ../helpers

ME=$(basename $0)

setup_sandbox

# Every switch VM (internet, spines and leaves) gets rp_filter=0,
# mirroring neutron's BGP CI (tempest-multinode-with-bgp): the
# kernel's reverse path validation (rp_filter >= 1, loose mode
# included) drops the asymmetric return traffic of BGP-2-the-host
# floating IPs whenever the chassis advertising the /32 host route
# differs from the one egressing the reply (the floating IPs of a
# distributed router egress from the VM's compute node, while the
# connected-as-host announce tracks the gateway port's chassis).
run_setup start
assert_eq "ikvswitch-setup start rc" "${SETUP_RC}" "0"
for vm in internet spine1 spine2 leaf1 leaf2 leaf3 leaf4 leaf5 leaf6 ; do
	F=$(ls ${SANDBOX}/out/${vm}/etc/sysctl.d/*rp-filter* 2>/dev/null | head -1)
	if [ -z "${F}" ] ; then
		echo "${ME}: ${vm} has no rp-filter sysctl file"
		exit 1
	fi
	assert_file_contains "${vm} all rp_filter" "${F}" "net.ipv4.conf.all.rp_filter=0"
	assert_file_contains "${vm} default rp_filter" "${F}" "net.ipv4.conf.default.rp_filter=0"
	assert_file_contains "${vm} glob rp_filter" "${F}" "net.ipv4.conf.*.rp_filter=0"

	# The file must sort after the stock Debian files setting rp_filter
	# to 2 (10-network-security.conf for default, and since systemd 257
	# 50-default.conf for default AND the per-interface glob
	# net.ipv4.conf.*.rp_filter): sysctl.d precedence is lexicographic
	# and the latest file wins a key. The glob at 2 is re-expanded at
	# every sysctl application (boot or a manual "sysctl --system") and
	# re-writes 2 into every interface existing at that moment, behind
	# the back of the ifupdown hook; this file's own glob at 0 wins the
	# key at every application and ends the race for good.
	if [ "10-network-security.conf" \> "$(basename ${F})" ] ; then
		echo "${ME}: ${vm}: $(basename ${F}) sorts before 10-network-security.conf"
		exit 1
	fi

	# As a second belt, the setup injects an "ip-rp-filter 0" option in
	# EVERY iface stanza of the generated /etc/network/interfaces,
	# honored by the ifupdown package's if-up.d/ip hook at the exact
	# moment the interface is brought up (an interface raised after the
	# sysctl run inherits default=0 and gets the knob value written):
	# one option line per iface stanza, no more, no less.
	I=${SANDBOX}/out/${vm}/etc/network/interfaces
	assert_eq "${vm} iface stanza rp_filter balance" \
		"$(grep -c '^iface ' ${I})" "$(grep -c 'ip-rp-filter 0' ${I})"
done

# The knob is optional: IFACE_RP_FILTER set to an empty value disables
# the option injection entirely (the pre-knob behavior).
reset_conf
echo 'IFACE_RP_FILTER=""' >>${SANDBOX}/etc/ikvswitch.conf
run_setup start
assert_eq "ikvswitch-setup start rc (knob disabled)" "${SETUP_RC}" "0"
for vm in internet spine1 spine2 leaf1 leaf2 leaf3 leaf4 leaf5 leaf6 ; do
	I=${SANDBOX}/out/${vm}/etc/network/interfaces
	assert_eq "${vm} no ip-rp-filter when disabled" \
		"$(grep -c 'ip-rp-filter' ${I} 2>/dev/null || true)" "0"
done

exit 0
