#!/bin/sh

set -e

. ../helpers

ME=$(basename $0)

setup_sandbox

FRR_LEAF1=${SANDBOX}/out/leaf1/etc/frr/frr.conf
FRR_LEAF2=${SANDBOX}/out/leaf2/etc/frr/frr.conf
FRR_SPINE=${SANDBOX}/out/spine1/etc/frr/frr.conf

# The machine-facing import guard: the leaves must never trust a
# machine-announced default route (v4 or v6), nor the delegated host
# block. A machine re-exporting what it learned (an OVN chassis VRF
# redistributing a router-advertisement default, or a legacy machine
# redistributing its kernel table) announces a 1-AS path that beats
# the spines' 2-AS path, and the leaf's kernel default then points
# back at the machine: the ::/0 forwarding path loops and the whole
# rack loses its IPv6 egress.
run_setup start
assert_eq "ikvswitch-setup start rc" "${SETUP_RC}" "0"

assert_file_contains "leaf1 deny v4 default" "${FRR_LEAF1}" "route-map map-leaf-in deny 10"
assert_file_contains "leaf1 deny v4 default match" "${FRR_LEAF1}" " match ip address prefix-list pl-default"
assert_file_contains "leaf1 deny v6 default" "${FRR_LEAF1}" " match ipv6 address prefix-list pl-default6"
assert_file_contains "leaf1 deny delegated block" "${FRR_LEAF1}" " match ipv6 address prefix-list pl-delegated6"
assert_file_contains "leaf1 permit everything else" "${FRR_LEAF1}" "route-map map-leaf-in permit 100"

# The prefix-lists are rendered with the stock base (fd00:1:1 + "0"),
# so the /59 deny covers exactly the delegated aggregate and none of
# the machines' own /128s inside it.
assert_file_contains "leaf1 pl-default" "${FRR_LEAF1}" "ip prefix-list pl-default seq 5 permit 0.0.0.0/0"
assert_file_contains "leaf1 pl-default6" "${FRR_LEAF1}" "ipv6 prefix-list pl-default6 seq 5 permit ::/0"
assert_file_contains "leaf1 pl-delegated6" "${FRR_LEAF1}" "ipv6 prefix-list pl-delegated6 seq 5 permit fd00:1:10::/59"

# The guard is on the VLAN-enabled leaf too.
assert_file_contains "leaf2 deny delegated block" "${FRR_LEAF2}" " match ipv6 address prefix-list pl-delegated6"

# The spines' map-leaf-in faces the leaves and must keep trusting
# them: they relay the fabric's legitimate defaults.
assert_file_not_contains "spine map-leaf-in unguarded" "${FRR_SPINE}" "route-map map-leaf-in deny"
assert_file_contains "spine map-leaf-in still trusts" "${FRR_SPINE}" "route-map map-leaf-in permit 10"

# A user-owned base override flows through the guard's prefix-list.
cat >>${SANDBOX}/etc/ikvswitch-local.conf <<EOF
HOST_VIRTUAL_SUBNET_START_PREFIX_V6=fd00:2:1
EOF
run_setup start
assert_eq "start with overridden base rc" "${SETUP_RC}" "0"
assert_file_contains "leaf1 pl-delegated6 overridden" "${FRR_LEAF1}" "ipv6 prefix-list pl-delegated6 seq 5 permit fd00:2:10::/59"

exit 0
