#!/usr/bin/make -f

# enable Debian Hardening
# see: https://wiki.debian.org/Hardening
export DEB_BUILD_MAINT_OPTIONS = hardening=+all
export DEB_BUILD_HARDENING = 1
DPKG_EXPORT_BUILDFLAGS = 1
include /usr/share/dpkg/default.mk

# Use bundled asio, since system asio is too new (> 1.10.8)
SCONS_ARGS += system_asio=0

# Parallel build support as adviced
# at https://www.debian.org/doc/debian-policy/ch-source.html#s-debianrules-options
ifneq (,$(filter parallel=%,$(DEB_BUILD_OPTIONS)))
	NUMJOBS = $(patsubst parallel=%,%,$(filter parallel=%,$(DEB_BUILD_OPTIONS)))
	SCONS_ARGS += -j$(NUMJOBS)
	# Don't use MAKEFLAGS as it has strange 'w' and '--jobserver-fds=3,4' by default
endif

# According to Debian Policy version 4.2.0 builds should be as verbose as
# possible unless 'terse' is specifically passed.
ifeq (,$(filter terse,$(DEB_BUILD_OPTIONS)))
	SCONS_ARGS += VERBOSE=1
	export DH_VERBOSE=1
endif

# Tests are run by default sometimes, so explicitly enable or disable them
ifeq (,$(filter nocheck,$(DEB_BUILD_OPTIONS)))
# Bus errors on arm64 kernels prevent running testsuite when building armhf
ifeq (armhf,$(DEB_HOST_ARCH))
	SCONS_ARGS += tests=0 deterministic_tests=0
else
	SCONS_ARGS += tests=1 deterministic_tests=1
endif
else
	SCONS_ARGS += tests=0 deterministic_tests=0
endif

# Use strict compilation flags (ie -Werror) if requested
ifneq (,$(filter strict_build_flags,$(DEB_BUILD_OPTIONS)))
	SCONS_ARGS += strict_build_flags=1
endif

# Some mipsel buildd's are a bit slow and fail tests if they are not
# given enough time
ifeq (mipsel,$(DEB_HOST_ARCH))
        export CK_TIMEOUT_MULTIPLIER=2
endif

override_dh_auto_build:
	# Print build env info to help debug builds on different platforms
	dpkg-architecture
	@echo $(SCONS_ARGS)
	scons $(SCONS_ARGS) || touch FAIL # Print config.log if build fails
	@echo '*****************************************'
	@echo '**  config.log contents for debugging  **'
	@echo '*****************************************'
	@cat config.log
	@echo '*****************************************'
	if [ -f FAIL ]; then exit 1; fi

# Start earlier than MySQL which has value 19
override_dh_installinit-arch:
	dh_installinit -n --name=garb -- defaults 18 22

override_dh_installsystemd:
	dh_installsystemd --name=garb

%:
	dh $@
