# #-- subnet_cache_lookup.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="../.."
# do the test
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 "> cat logfiles"
#cat fwd.log 
#cat unbound.log
echo "> check answer"
if grep www.example.com outfile | grep "10.20.30.40"; then
	echo "OK"
else
	echo "Not OK"
	exit 1
fi

echo "> unbound-control status"
$PRE/unbound-control -c ub.conf status
if test $? -ne 0; then
	echo "wrong exit value."
	exit 1
else
	echo "exit value: OK"
fi

echo "> unbound-control cache_lookup example.com"
$PRE/unbound-control -c ub.conf cache_lookup example.com 2>&1 | tee outfile
if test $? -ne 0; then
	echo "wrong exit value."
	exit 1
fi
echo "> check unbound-control output"
if grep "subnet" outfile; then
	echo "OK"
else
	echo "Not OK"
	exit 1
fi

echo "> use proxy-protocol to put more addresses in the edns subnet cache"
$PRE/streamtcp -f 127.0.0.1@$PROXY_PORT -p 1.1.3.4 www.example.net. A IN | tee outfile
if grep www.example.net outfile | grep "10.20.30.41"; then
	echo "OK"
else
	echo "Not OK"
	exit 1
fi

$PRE/streamtcp -f 127.0.0.1@$PROXY_PORT -p 1.2.3.4 www.example.net. A IN | tee outfile
if grep www.example.net outfile | grep "10.20.30.42"; then
	echo "OK"
else
	echo "Not OK"
	exit 1
fi

$PRE/streamtcp -f 127.0.0.1@$PROXY_PORT -p 1.3.3.4 www.example.net. A IN | tee outfile
if grep www.example.net outfile | grep "10.20.30.43"; then
	echo "OK"
else
	echo "Not OK"
	exit 1
fi

$PRE/streamtcp -f 127.0.0.1@$PROXY_PORT -p 1.4.3.4 www.example.net. A IN | tee outfile
if grep www.example.net outfile | grep "10.20.30.44"; then
	echo "OK"
else
	echo "Not OK"
	exit 1
fi

echo "> unbound-control cache_lookup example.net"
$PRE/unbound-control -c ub.conf cache_lookup example.net 2>&1 | tee outfile
if test $? -ne 0; then
	echo "wrong exit value."
	exit 1
fi
echo "> check unbound-control output"
if grep "subnet" outfile; then
	echo "OK"
else
	echo "Not OK"
	exit 1
fi

exit 0
