#!/usr/bin/make -f

export DEB_BUILD_MAINT_OPTIONS=optimize=+lto

include /usr/share/dpkg/default.mk

# NB: We do not build GraphBLAS, because it is provided by src:suitesparse-graphblas
# (see do-not-build-graphblas.patch)

# We can’t rely on dh_auto_*, because the build system uses a mix of traditional Makefiles and cmake

# Build type defined to “None”, as in /usr/share/perl5/Debian/Debhelper/Buildsystem/cmake.pm
# Buildflags are taken from the environment
CMAKE_OPTIONS := -DCMAKE_INSTALL_PREFIX=/usr \
		-DCMAKE_BUILD_TYPE=None \
		-DBLA_PREFER_PKGCONFIG=TRUE \
		-DSUITESPARSE_CUDA=FALSE
ifeq (,$(filter terse,$(DEB_BUILD_OPTIONS)))
CMAKE_OPTIONS += -DCMAKE_VERBOSE_MAKEFILE=ON
endif

# CMake does not use CPPFLAGS
export CFLAGS := $(CFLAGS) $(CPPFLAGS)
export CXXFLAGS := $(CXXFLAGS) $(CPPFLAGS)

PDF_DOCS := AMD/Doc/AMD_UserGuide.pdf CAMD/Doc/CAMD_UserGuide.pdf CHOLMOD/Doc/CHOLMOD_UserGuide.pdf KLU/Doc/KLU_UserGuide.pdf Mongoose/Doc/Mongoose_UserGuide.pdf UMFPACK/Doc/UMFPACK_QuickStart.pdf UMFPACK/Doc/UMFPACK_UserGuide.pdf LDL/Doc/ldl_userguide.pdf SPQR/Doc/spqr_user_guide.pdf SPEX/Doc/SPEX_UserGuide.pdf

ifneq (,$(filter parallel=%,$(DEB_BUILD_OPTIONS)))
JOBS := $(patsubst parallel=%,%,$(filter parallel=%,$(DEB_BUILD_OPTIONS)))
else
JOBS := 1
endif

%:
	dh $@

override_dh_auto_configure:

# It’s necessary to build the libraries even in an indep-only build, because
# otherwise CMake complains about missing libsuitesparseconfig when building
# the docs.
# What matters is that docs are not built in arch-only build (see #960766).
build-stamp:
	make CMAKE_OPTIONS='$(CMAKE_OPTIONS)' JOBS=$(JOBS)
	touch build-stamp

override_dh_auto_build-arch: build-stamp

override_dh_auto_build-indep: build-stamp
	rm -f $(PDF_DOCS)
ifeq (,$(filter nodoc,$(DEB_BUILD_OPTIONS)))
	make CMAKE_OPTIONS='$(CMAKE_OPTIONS)' JOBS=$(JOBS) docs
endif

override_dh_auto_install-arch:
	make install DESTDIR=$$(pwd)/debian/tmp
	# Remove CUDA stuff that we don’t need
	cd debian/tmp/usr/lib && \
		rm */libgpuqrengine.* */libsuitesparse_gpuruntime.* \
			*/pkgconfig/GPUQREngine.pc */pkgconfig/SuiteSparse_GPURuntime.pc
	cd debian/tmp/usr/include && \
		rm GPUQREngine.hpp SuiteSparse_GPURuntime.hpp

override_dh_auto_install-indep:

override_dh_auto_test-arch:
ifeq (,$(filter nocheck,$(DEB_BUILD_OPTIONS)))
	make CMAKE_OPTIONS='$(CMAKE_OPTIONS)' JOBS=$(JOBS) demos
endif

override_dh_auto_test-indep:

override_dh_auto_clean:
	make purge
	# Workaround for https://github.com/DrTimothyAldenDavis/SuiteSparse/issues/502
	make -C CHOLMOD/Doc purge
	rm -f $(PDF_DOCS)
	rm -f build-stamp

override_dh_compress:
	dh_compress -X.pdf
