#!/usr/bin/make -f

export DEB_BUILD_MAINT_OPTIONS = hardening=+all
include /usr/share/dpkg/buildflags.mk
CFLAGS+=$(CPPFLAGS)
CXXFLAGS+=$(CPPFLAGS)
DPKG_EXPORT_BUILDFLAGS = 1
include /usr/share/dpkg/architecture.mk

# Getting the number of jobs for the Debian build to transmit it to CMake.
ifneq (,$(filter parallel=%,$(DEB_BUILD_OPTIONS)))
	NUMJOBS = $(patsubst parallel=%,%,$(filter parallel=%,$(DEB_BUILD_OPTIONS)))
	test_makeflags = -j$(NUMJOBS)
endif

# On mips64el, deactivating Dlib tests (seems to be a bug in Dlib)
ifeq ($(shell dpkg --print-architecture),mips64el)
    test_discardflags := -E \\\"Dlib_.*\\\"
endif

# On ppc64el, deactivating the Kriging test (can be quite sensitive)
# and Dlib ones (seems to be a bug in Dlib).
ifeq ($(shell dpkg --print-architecture),ppc64el)
    test_discardflags := -E \\\"KrigingAlgorithm_std|Dlib_.*\\\"
endif

# On riscv64, deactivating Dlib tests (seems to be a bug in Dlib)
ifeq ($(shell dpkg --print-architecture),riscv64)
    test_discardflags := -E \\\"Dlib_.*\\\"
endif

BUILD_DATE = $(shell date --utc --date="@$(SOURCE_DATE_EPOCH)" "+%a, %d %b %Y %H:%M:%S %z")

%:
	dh $@ --buildsystem=cmake --with python3

override_dh_auto_configure:
	dh_auto_configure -Bbuilddir -- \
	        -DUSE_TBB:BOOL=ON \
            -Dot_configure_date:STRING='$(BUILD_DATE)' \
            -DUSE_SPHINX:BOOL=OFF \
            -DCMAKE_SKIP_INSTALL_RPATH:BOOL=ON \
            -DCMAKE_INSTALL_PREFIX:PATH=/usr \
            -DCMAKE_INSTALL_LIBDIR:PATH="/usr/lib/$(DEB_HOST_MULTIARCH)" \
            -DINSTALL_DESTDIR:PATH=$(CURDIR)/debian/tmp \
	        -DCMAKE_UNITY_BUILD=ON -DCMAKE_UNITY_BUILD_BATCH_SIZE=32 \
            -DSWIG_COMPILE_FLAGS:STRING='-O1'

override_dh_auto_build:
	$(MAKE) $(test_makeflags) -C builddir/lib
	$(MAKE) -j1 -C builddir/python
	$(MAKE) $(test_makeflags) -C builddir

override_dh_auto_install:
	dh_auto_install -Bbuilddir
ifeq (,$(findstring nocheck,$(DEB_BUILD_OPTIONS)))
	eval "LD_LIBRARY_PATH=$${LD_LIBRARY_PATH:+$${LD_LIBRARY_PATH}:}$(CURDIR)/debian/tmp/usr/lib/$(DEB_HOST_MULTIARCH) \
	  CTEST_OUTPUT_ON_FAILURE=1 \
	  $(MAKE) $(test_makeflags) -C builddir test ARGS=\"$(test_makeflags) $(test_discardflags) -R pyinstallcheck\""
endif

override_dh_auto_test:
	# 'make test' does not build binary tests
ifeq (,$(findstring nocheck,$(DEB_BUILD_OPTIONS)))
	$(MAKE) $(test_makeflags) -C builddir tests
	eval "CTEST_OUTPUT_ON_FAILURE=1 \
	  $(MAKE) -C builddir test ARGS=\"$(test_makeflags) $(test_discardflags) -R cppcheck\""
endif

override_dh_clean:
	rm -rf builddir
	dh_clean
