#!/usr/bin/make -f

BUILDHOME = $(CURDIR)/debian/build
PIDFILE = $(BUILDHOME)/mongod.pid
PORT := $(shell /bin/netstat -want | perl -w -e 'while (<>) { $$used{$$1}=1 if /127\.0\.0\.1:(\d+)/;}; $$port = 12345; while ($$used{$$port}) { $$port++ }; print "$$port\n";')

# pass PORT to test through MONGOD variable in t/lib/MongoDBTest.pm
MONGOD = localhost:$(PORT)

export DEB_BUILD_MAINT_OPTIONS = hardening=+all

%:
	dh $@

override_dh_auto_test:
	mkdir -p $(BUILDHOME)
	# mongod is required during build only on i386 amd64
	# "until netstat" command wait for mongod to be listening on PORT
	if [ -x /usr/bin/mongod ]; then \
	  mongod --dbpath $(BUILDHOME) --noprealloc --bind_ip 127.0.0.1 --nojournal --port $(PORT) --quiet --fork --logpath $(BUILDHOME)/mongod.log --pidfilepath $(PIDFILE); \
	  i=10; \
	  until (/bin/netstat -want | grep -q 127.0.0.1:$(PORT) ) || [ $$i = 0 ]; do sleep 1; i=$$((i-1)); echo waiting for mongod; done \
	fi
	export MONGOD=127.0.0.1:$(PORT);\
	dh_auto_test
	# The server process might not have actually started
	[ ! -s $(PIDFILE) ] || /bin/kill `cat $(PIDFILE)` || true

override_dh_clean:
	dh_clean
	rm -rf $(BUILDHOME)