#!/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 --ssl --nostrip $(DEB_SCONS_OPTIONS)

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

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

# NOTE: disable javascript scripting support
COMMON_OPTIONS += --disable-scripting

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)

ifeq (,$(findstring nocheck, $(DEB_BUILD_OPTIONS)))
override_dh_auto_test:
	scons $(DEB_SCONS_CHECK)
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
