#!/usr/bin/make -f
# -*- makefile -*-

# Uncomment this to turn on verbose mode.
#export DH_VERBOSE=1

DEB_SCONS_OPTIONS :=
ifneq (,$(findstring debug,$(DEB_BUILD_OPTIONS)))
	DEB_SCONS_OPTIONS := --d=DEBUGBUILD
endif
ifneq (,$(findstring nostrip,$(DEB_BUILD_OPTIONS)))
	DEB_SCONS_OPTIONS := --d=DEBUGBUILD
endif
ifneq (,$(findstring parallel,$(DEB_BUILD_OPTIONS)))
       PROCS=$(patsubst parallel=%,%,$(filter parallel=%,$(DEB_BUILD_OPTIONS)))
       DEB_SCONS_OPTIONS += -j$(PROCS)
endif

HARDENING_OPTIONS = CC="$(CC)" CFLAGS="$(CFLAGS)" \
  CXX="$(CXX)" CXXFLAGS="$(CXXFLAGS)"
COMMON_OPTIONS = --use-system-snappy --use-system-pcre \
  --use-system-boost --use-system-v8 --ssl $(DEB_SCONS_OPTIONS)

gperftools_archs = amd64 i386 armhf ppc64el
ifneq (,$(filter $(DEB_HOST_ARCH), $(gperftools_archs)))
COMMON_OPTIONS += --allocator=tcmalloc --use-system-tcmalloc
else
COMMON_OPTIONS += --allocator=system
endif

ifeq ($(DEB_HOST_ARCH), arm64)
COMMON_OPTIONS += --disable-scripting
endif

DEB_SCONS_CLEAN = --directory="." $(HARDENING_OPTIONS) . --keep-going --clean \
  $(COMMON_OPTIONS)
DEB_SCONS_BUILD = --directory="." $(HARDENING_OPTIONS) all $(COMMON_OPTIONS)
DEB_SCONS_CHECK = --smokedbprefix=$(CURDIR)/debian/tmp-test smoke \
  $(COMMON_OPTIONS)
DEB_SCONS_INSTALL = --directory="." $(HARDENING_OPTIONS) \
  --prefix=$(CURDIR)/debian/tmp/usr install --full $(COMMON_OPTIONS)

override_dh_clean:
	scons $(DEB_SCONS_CLEAN)
	find $(CURDIR)/ -name "*.pyc" -delete
	rm -rf $(CURDIR)/debian/tmp-test/
	rm -rf $(CURDIR)/.scons/
	rm -rf $(CURDIR)/build/
	rm -f $(CURDIR)/failfile.smoke $(CURDIR)/smoke-last.json
	dh_clean

override_dh_auto_build:
	scons $(DEB_SCONS_BUILD)

override_dh_auto_test:
	scons $(DEB_SCONS_CHECK)

override_dh_auto_install:
	scons $(DEB_SCONS_INSTALL)

override_dh_installinit:
	dh_installinit -pmongodb-server --name=mongodb

ifeq ($(DEB_HOST_ARCH), arm64)
# mongo shell is broken without scripting so drop it from
# the binary
override_dh_install:
	dh_install
	rm -f $(CURDIR)/tmp/mongodb-clients/usr/bin/mongo
endif

%:
	dh $@ --parallel

.PHONY: override_dh_clean override_dh_auto_build override_dh_auto_test \
	override_dh_auto_install override_dh_installinit
