# #-- dynlibmod.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

. ../common.sh
PRE="../.."
if grep "define WITH_DYNLIBMODULE 1" $PRE/config.h; then echo test enabled; else echo test skipped; exit 0; fi

# compile the dynamic library module
if grep "define USE_WINSOCK 1" $PRE/config.h; then
	echo "compile dynamic library dll for mingw"
	echo "x86_64-w64-mingw32-gcc -m64 -I$PRE -shared -Wall -fpic -o helloworld.dll $PRE/dynlibmod/examples/helloworld.c -L../.. -l:libunbound.a"
	x86_64-w64-mingw32-gcc -m64 -I$PRE -shared -Wall -fpic -o helloworld.dll $PRE/dynlibmod/examples/helloworld.c -L../.. -l:libunbound.a
	if test $? != 0; then
		echo "compile failure"
		exit 1;
	fi
else
	echo "compile dynamic library"
	echo "gcc -I$PRE -shared -Wall -fpic -o helloworld.so $PRE/dynlibmod/examples/helloworld.c"
	gcc -I$PRE -shared -Wall -fpic -o helloworld.so $PRE/dynlibmod/examples/helloworld.c
	if test $? != 0; then
		echo "compile failure"
		exit 1;
	fi
fi

# start unbound in the background
LD_LIBRARY_PATH="." $PRE/unbound -d -c ub.conf >unbound.log 2>&1 &
UNBOUND_PID=$!
echo "UNBOUND_PID=$UNBOUND_PID" >> .tpkg.var.test
wait_unbound_up unbound.log

# test if the server is up.
echo "> dig www.example.com."
dig @127.0.0.1 -p $UNBOUND_PORT www.example.com. | tee outfile
echo "> check answer"
if grep "10.20.30.40" outfile; then
	echo "OK"
else
	echo "> cat logfiles"
	cat fwd.log
	cat unbound.log
	echo "Not OK"
	exit 1
fi

echo "> check log for dynlibmod info"
# wait for a moment for filesystem to catch up.
if grep "hello world from operate" unbound.log >/dev/null; then :; else sleep 1; fi
if grep "hello world from operate" unbound.log >/dev/null; then :; else sleep 1; fi
if grep "hello world from operate" unbound.log >/dev/null; then :; else sleep 1; fi
if grep "hello world from operate" unbound.log >/dev/null; then :; else sleep 1; fi
if grep "hello world from operate" unbound.log >/dev/null; then :; else sleep 1; fi
if grep "hello world from operate" unbound.log >/dev/null; then :; else sleep 1; fi
if grep "hello world from operate" unbound.log >/dev/null; then :; else sleep 10; fi
if grep "hello world from operate" unbound.log; then echo "yes it is in unbound.log";
else
	echo "information not in unbound.log"
	echo "failed"
	echo "> cat logfiles"
	cat fwd.log
	cat unbound.log
	echo "Not OK"
	exit 1
fi

echo "> cat logfiles"
cat fwd.log
cat unbound.log
echo "> OK"
exit 0
