# #-- http_user_agent.test --#
# source the master var file when it's there
[ -f ../.tpkg.var.master ] && source ../.tpkg.var.master
# use .tpkg.var.test for in test variable passing
[ -f .tpkg.var.test ] && source .tpkg.var.test

PRE="../.."

# Query and check check that we get the correct answer from the auth_zone
query () {
	echo "> dig www.example.com."
	dig @127.0.0.1 -p $UNBOUND_PORT www.example.com. | tee outfile
	if grep SERVFAIL outfile; then
		echo "> try again"
		dig @127.0.0.1 -p $UNBOUND_PORT www.example.com. | tee outfile
	fi
	if grep SERVFAIL outfile; then
		echo "> try again"
		sleep 1
		dig @127.0.0.1 -p $UNBOUND_PORT www.example.com. | tee outfile
	fi
	if grep SERVFAIL outfile; then
		echo "> try again"
		sleep 1
		dig @127.0.0.1 -p $UNBOUND_PORT www.example.com. | tee outfile
	fi
	if grep SERVFAIL outfile; then
		echo "> try again"
		sleep 1
		dig @127.0.0.1 -p $UNBOUND_PORT www.example.com. | tee outfile
	fi
	if grep SERVFAIL outfile; then
		echo "> try again"
		sleep 10
		dig @127.0.0.1 -p $UNBOUND_PORT www.example.com. | tee outfile
	fi
	if grep SERVFAIL outfile; then
		echo "> try again"
		sleep 10
		dig @127.0.0.1 -p $UNBOUND_PORT www.example.com. | tee outfile
	fi
	echo "> check answer"
	if grep "1.2.3.4" outfile; then
		echo "OK"
	else
		echo "Not OK"
		exit 1
	fi
}

# Reload the configuration and retransfer the zone
reload_and_retransfer () {
	echo "> Reloading Unbound"
	echo "$PRE/unbound-control -c ub.conf reload"
	$PRE/unbound-control -c ub.conf reload
	if test $? -ne 0; then
		echo "wrong exit value from unbound-control"
		exit 1
	fi
	echo "> Refetching example.com"
	echo "$PRE/unbound-control -c ub.conf auth_zone_transfer example.com"
	$PRE/unbound-control -c ub.conf auth_zone_transfer example.com
	if test $? -ne 0; then
		echo "wrong exit value from unbound-control"
		exit 1
	fi
}

# do the test
query
# add custom http-user-agent
echo "server: http-user-agent: customUA" >> ub.conf
reload_and_retransfer
query
# hide http-user-agent
echo "server: hide-http-user-agent: yes" >> ub.conf
reload_and_retransfer
query

echo "> cat logfiles"
cat petal.log 
cat unbound.log

# check petal.log for the correct number of occurrences.
# It should be 2 User-Agents, one being the custom.
echo "> check User-Agent occurrences"
occurrences=`grep "User-Agent:" petal.log | wc -l`
echo $occurrences
if test $occurrences -eq 2; then
	echo "OK"
else
	echo "Not OK"
	exit 1
fi
echo "> check custom User-Agent"
if grep "User-Agent: customUA" petal.log; then
	echo "OK"
else
	echo "Not OK"
	exit 1
fi

exit 0
