#!/bin/sh

set -e

. ../helpers

ME=$(basename $0)

setup_sandbox

CONF_LEAF1=${SANDBOX}/out/leaf1/etc/dnsmasq.d/ikvswitch.conf
FRR_INTERNET=${SANDBOX}/out/internet/etc/frr/frr.conf

# The user-owned values file carries the DHCP domain and resolvers:
# editing it changes what the generated configuration holds.
cat >>${SANDBOX}/etc/ikvswitch-local.conf <<EOF
DHCP_DOMAIN_NAME=test.example
DHCP_DNS_SERVERS=192.0.2.53,192.0.2.54
EOF
run_setup start
assert_eq "ikvswitch-setup start rc" "${SETUP_RC}" "0"
assert_file_contains "leaf1 domain from -local" "${CONF_LEAF1}" "dhcp-option=15,test.example"
assert_file_contains "leaf1 resolvers from -local" "${CONF_LEAF1}" "dhcp-option=6,192.0.2.53,192.0.2.54"

# The stock file is sourced LAST: a variable set in both files takes
# the stock value, which is why the user-owned variables are removed
# from ikvswitch.conf. AS_START is a stock variable: setting it in
# the local file must have no effect.
cat >>${SANDBOX}/etc/ikvswitch-local.conf <<EOF
AS_START=65400
EOF
run_setup start
assert_eq "ikvswitch-setup start rc (clobber)" "${SETUP_RC}" "0"
assert_file_contains "internet stock AS wins over -local" "${FRR_INTERNET}" "router bgp 65500"
assert_file_not_contains "internet -local AS ignored" "${FRR_INTERNET}" "router bgp 65400"

# A missing local file is fatal: the user-owned variables are defined
# nowhere else, so the scripts refuse to run without it.
reset_conf
rm -f "${SANDBOX}/etc/ikvswitch-local.conf"
run_setup start
assert_eq "ikvswitch-setup start rc (no -local)" "${SETUP_RC}" "1"
assert_contains "missing -local error" "${OUT}" "Could not read ${SANDBOX}/etc/ikvswitch-local.conf"
