#!/bin/sh

set -e

. ./helpers

ME=$(basename $0)

setup_sandbox

RUNT=${SANDBOX}/var/lib/ikvswitch/runtime
LEAF1=${RUNT}/leaf1.ipmisim.conf
IFACES=${SANDBOX}/out/leaf1/etc/network/interfaces
FRR=${SANDBOX}/out/leaf1/etc/frr/frr.conf
FRR_SPINE1=${SANDBOX}/out/spine1/etc/frr/frr.conf

# The switch VMs run with the q35 machine type, and every PCI device
# has a pinned address: the SCSI controller at 0x3, then one slot per
# NIC from 0x4 on. The guest consequently names its interfaces enp0s4,
# enp0s5, ... whatever the machine type, so the generated network and
# FRR configurations match what the kernel really provides.
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
	CONF=${RUNT}/${VM}.ipmisim.conf
	assert_file_contains "${VM} q35 machine" "${CONF}" "-machine q35"
	assert_file_contains "${VM} scsi controller at 0x3" "${CONF}" "virtio-scsi-pci,id=scsi0,addr=0x3"
	NICS=$(grep -o "virtio-net-pci,netdev=" ${CONF} | wc -l)
	ADDRESSES=$(grep -o "addr=0x" ${CONF} | wc -l)
	assert_eq "${VM} every NIC has a pinned addr" "${ADDRESSES}" "$(( ${NICS} + 1 ))"
done

# The leaves pin their spine-facing NICs at 0x4 and 0x5, then their
# server facing ports from 0x6 (rack position 3) to 0x1A (position 23).
assert_file_contains "leaf1 first NIC at 0x4" "${LEAF1}" "addr=0x4"
assert_file_contains "leaf1 last NIC at 0x1A" "${LEAF1}" "addr=0x1A"

# The guest side uses the enp0sN names, and no ens name remains.
assert_file_contains "leaf1 spine NIC in interfaces" "${IFACES}" "auto enp0s4"
assert_file_contains "leaf1 dhcp0 bridge ports" "${IFACES}" "bridge_ports  enp0s6 enp0s7"
ENS_COUNT=$(grep -oE "ens[0-9]" ${IFACES} | wc -l)
assert_eq "leaf1 no ens name in interfaces" "${ENS_COUNT}" "0"
assert_file_contains "leaf1 spine neighbor in frr" "${FRR}" "neighbor enp0s4 interface peer-group spine"
assert_file_contains "leaf1 vlan neighbor in frr" "${FRR}" "neighbor enp0s6.10 interface peer-group leaf"
ENS_COUNT=$(grep -oE "ens[0-9]" ${FRR} | wc -l)
assert_eq "leaf1 no ens name in frr" "${ENS_COUNT}" "0"
assert_file_contains "spine1 leaf neighbor in frr" "${FRR_SPINE1}" "neighbor enp0s5 interface peer-group leaf"
assert_file_contains "spine1 last leaf neighbor in frr" "${FRR_SPINE1}" "neighbor enp0s10 interface peer-group leaf"

exit 0
