#!/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-yaml --use-system-valgrind \
  --use-system-zlib --ssl --nostrip $(DEB_SCONS_OPTIONS)

ifneq ($(shell lsb_release -cs | sed -r 's/trusty/old/'),old)
	COMMON_OPTIONS += --use-system-boost
endif

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

# JUJU NOTE: disable javascript scripting support in the server; do not
# install the client.
COMMON_OPTIONS += --server-js=off

export DEB_HOST_ARCH ?= $(shell dpkg-architecture -qDEB_HOST_ARCH)

DEB_SCONS_CLEAN = --directory="." $(HARDENING_OPTIONS) . --keep-going --clean \
  $(COMMON_OPTIONS)
DEB_SCONS_BUILD = --directory="." $(HARDENING_OPTIONS) all $(COMMON_OPTIONS)
DEB_SCONS_INSTALL = --directory="." $(HARDENING_OPTIONS) \
  --prefix=$(CURDIR)/debian/tmp/usr install $(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

ifeq (,$(findstring nocheck, $(DEB_BUILD_OPTIONS)))
override_dh_auto_build:
	scons $(DEB_SCONS_BUILD)
endif

ifeq (,$(findstring nocheck, $(DEB_BUILD_OPTIONS)))
override_dh_auto_test:
	buildscripts/resmoke.py --suites=unittests \
		--dbpathPrefix $(CURDIR)/debian/tmp-test --storageEngine=mmapv1
endif

override_dh_auto_install:
	scons $(DEB_SCONS_INSTALL)

%:
	dh $@ --parallel

.PHONY: override_dh_clean override_dh_auto_build override_dh_auto_test \
	override_dh_auto_install
