# -*- shell-script -*-

FUNCTIONS_DIR="debian/tests/functions.d"

match_or_exit () {
	file_to_match="$1"
	pattern_file="$2"

	while read line_to_match <&3 && read pattern_line <&4 ; do
		if [ "${line_to_match##$pattern_line}" ]; then
			echo '!!! MISMATCH !!!' >&2
			echo "Line:    ${line_to_match}" >&2
			echo "Pattern: ${pattern_line}" >&2
			exit 1
		fi;
	done 3<"${file_to_match}" 4<"${pattern_file}"
}

linecount () {
	wc -l $1 | cut -d' ' -f1
}

error_exit () {
	echo "ERROR: $1"
	exit 1
}

stop_dnsmasq_networking () {
	systemctl stop dnsmasq.service
	systemctl stop networking.service
}

configure_and_start_networking () {
	#Add interfaces needed for the test
	cat ${FUNCTIONS_DIR}/add-to.interfaces >> /etc/network/interfaces
	systemctl start networking.service
}

configure_and_start_bind () {
	cp ${FUNCTIONS_DIR}/db.autopkg.test /etc/bind/
	cat ${FUNCTIONS_DIR}/add-to.named.conf.local >> /etc/bind/named.conf.local
	cp ${FUNCTIONS_DIR}/named.conf.options /etc/bind/named.conf.options
	systemctl restart bind9.service
}

configure_and_start_dnsmasq () {
	alt_mode=0
	lua_mode=0
	sysv_mode=0
	service='dnsmasq.service'
	sysv_param2=''
	conf_dir='/etc/dnsmasq.d'

	cp ${FUNCTIONS_DIR}/dnsmasq-autopkgtest.conf "${conf_dir}"

	if [ ${lua_mode} -eq 1 ]; then
		mkdir -p /usr/local/share/dnsmasq
		cp ${FUNCTIONS_DIR}/log.lua /usr/local/share/dnsmasq/
		echo "dhcp-luascript=/usr/local/share/dnsmasq/log.lua\n" \
			>>"${conf_dir}"/dnsmasq-autopkgtest.conf
	fi

	if [ ${sysv_mode} -eq 1 ]; then
		SYSTEMCTL_SKIP_REDIRECT=1 /etc/init.d/dnsmasq start "${sysv_param2}"
	else
		systemctl enable "${service}"
		systemctl start "${service}"
	fi
}

check_compile_time_options () {
	journalctl -b -u dnsmasq
	echo ~~~ Check compile time options...
	journalctl -b -u dnsmasq | grep "compile time options" | awk -F':' '{print $NF}' >options.msg
	cat options.msg
	match_or_exit options.msg ${FUNCTIONS_DIR}/options${1}.patterns
}

get_address_on_veth1_and_check_the_result () {
	echo ~~~ Get an address on veth1 and check the result...
	ip netns exec clientnet ifup veth1
	ip netns exec clientnet ip addr show dev veth1 >ip-addr.out 2>&1
	cat ip-addr.out
	match_or_exit ip-addr.out ${FUNCTIONS_DIR}/ip-addr.patterns
}

query_test_zone_records_and_check_the_result () {
	echo ~~~ Query some test zone records and check the result...
	ip netns exec clientnet dig +short SOA autopkg.test >dig.out 2>&1
	ip netns exec clientnet dig +short NS autopkg.test >>dig.out 2>&1
	ip netns exec clientnet dig +short A ns.autopkg.test >>dig.out 2>&1
	ip netns exec clientnet dig +short A dhcp3.autopkg.test >>dig.out 2>&1
	cat dig.out
	if [ `linecount dig.out` -ne `linecount ${FUNCTIONS_DIR}/dig.patterns` ] ; then
		error_exit 'empty or unexpected output'
	fi
	match_or_exit dig.out ${FUNCTIONS_DIR}/dig.patterns
}
