#!/bin/sh

set -e

. ./helpers

ME=$(basename $0)

setup_sandbox

# A mandatory option missing from the configuration file must stop the
# start, with a message naming the variable.
reset_conf
grep -v '^DHCP_POOL_START=' "${SANDBOX}/etc/ikvswitch.conf" >"${SANDBOX}/etc/ikvswitch.conf.new"
mv "${SANDBOX}/etc/ikvswitch.conf.new" "${SANDBOX}/etc/ikvswitch.conf"
run_setup start
assert_eq "missing option rc" "${SETUP_RC}" "1"
assert_contains "missing option message" "${OUT}" "Please set DHCP_POOL_START"
assert_not_contains "missing option message" "${OUT}" "Customizing template"

# An invalid DHCP_SERVER_DAEMON must be rejected as well.
reset_conf
sed -i -e 's/^DHCP_SERVER_DAEMON=.*/DHCP_SERVER_DAEMON=bogus/' "${SANDBOX}/etc/ikvswitch.conf"
run_setup start
assert_eq "invalid daemon rc" "${SETUP_RC}" "1"
assert_contains "invalid daemon message" "${OUT}" "DHCP_SERVER_DAEMON must be either dnsmasq or isc-dhcp"

# So must a DHCP_HTTP_BOOT_URL which is not an HTTP URL.
reset_conf
sed -i -e 's|^DHCP_HTTP_BOOT_URL=.*|DHCP_HTTP_BOOT_URL=ftp://192.168.100.2/x|' "${SANDBOX}/etc/ikvswitch.conf"
run_setup start
assert_eq "invalid URL rc" "${SETUP_RC}" "1"
assert_contains "invalid URL message" "${OUT}" "DHCP_HTTP_BOOT_URL must start with http:// or https://"

# A configuration file without any DHCP_SERVER_DAEMON keeps working:
# it falls back to dnsmasq.
reset_conf
grep -v '^DHCP_SERVER_DAEMON=' "${SANDBOX}/etc/ikvswitch.conf" >"${SANDBOX}/etc/ikvswitch.conf.new"
mv "${SANDBOX}/etc/ikvswitch.conf.new" "${SANDBOX}/etc/ikvswitch.conf"
run_setup start
assert_eq "daemon fallback rc" "${SETUP_RC}" "0"
assert_file_contains "dnsmasq fallback" "${SANDBOX}/out/leaf1/etc/dnsmasq.d/ikvswitch.conf" "dhcp-boot=tag:ipxe,http://192.168.100.2/oci/ipxe.php"

# Stopping the lab must always work, even with a broken configuration
# file, as tearing down must not depend on it.
reset_conf
grep -v '^DHCP_POOL_START=' "${SANDBOX}/etc/ikvswitch.conf" >"${SANDBOX}/etc/ikvswitch.conf.new"
mv "${SANDBOX}/etc/ikvswitch.conf.new" "${SANDBOX}/etc/ikvswitch.conf"
run_setup stop
assert_eq "stop with broken conf rc" "${SETUP_RC}" "0"
assert_contains "stop output" "${OUT}" "All done"

exit 0
