#!/usr/bin/make -f

command = $(shell /bin/sh -c "command -v $(1)")

ifneq (,$(call command, pybuild))
DH_OPTIONS += --buildsystem=pybuild
PYTHON3 := $(shell pybuild --system distutils --print {interpreter.include_dir})
endif

%:
	dh $@ $(DH_OPTIONS)

# With gcc-11 -fstack-protector-strong:
# gnatbind -n -static use_c2phc -o use_c2phc_binder.adb
# raised STORAGE_ERROR : stack overflow or erroneous memory access
DEB_BUILD_MAINT_OPTIONS = hardening=+all,-stackprotectorstrong optimize=-lto

# drop back to C++14 (https://github.com/janverschelde/PHCpack/issues/55)
DEB_CXXFLAGS_MAINT_APPEND = -std=gnu++14

DPKG_EXPORT_BUILDFLAGS = 1
include /usr/share/dpkg/buildflags.mk
# This line has no effect during architecture-independent builds:
include $(wildcard /usr/share/ada/packaging.mk)

export PYBUILD_DIR = src/Python/PHCpy3

override_dh_auto_build-arch:
	@echo "+------------------+"
	@echo "| building PHCpack |"
	@echo "+------------------+"
	gprbuild $(GPRBUILDFLAGS) src/Ada/Main/main.gpr -o phc
	$(MAKE) -C src/doc man
ifeq (,$(filter nopython, $(DEB_BUILD_PROFILES)))
	@echo "+----------------+"
	@echo "| building PHCpy |"
	@echo "+----------------+"
	cd src/Ada/Main && gprclean main.gpr # so we can recompile with -fPIC
	$(MAKE) -C src/Objects phcpy2c3.so \
		PYTHON3=$(PYTHON3)         \
		GNATFLAGS="$(ADAFLAGS)"
	pybuild --build
ifeq (,$(filter nodoc, $(DEB_BUILD_PROFILES)))
	@echo "+---------------------+"
	@echo "| building PHCpy docs |"
	@echo "+---------------------+"
	$(MAKE) -C src/Python/PHCpy3/doc html
	jdupes -l src/Python/PHCpy3/doc/build/html/_images/math
endif
endif

ifeq (,$(filter nodoc, $(DEB_BUILD_PROFILES)))
override_dh_auto_build-indep:
	@echo "+-----------------------+"
	@echo "| building PHCpack docs |"
	@echo "+-----------------------+"
	$(MAKE) -C src/doc html
endif

# skip upstream test suite for now
# https://github.com/janverschelde/PHCpack/issues/41
# override_dh_auto_test:
#	$(MAKE) -C src/Objects testall

execute_before_dh_octave_version: DESCRIPTION

execute_after_dh_auto_install-indep: DESCRIPTION
	@echo "+-----------------+"
	@echo "| building PHClab |"
	@echo "+-----------------+"

	cp --update --reflink=auto src/Octave/COPYING.txt COPYING

	mkdir --parents inst
	cp --update --reflink=auto src/Octave/*.m debian/PKG_ADD inst

	dh_auto_install --buildsystem=octave

include /usr/share/dpkg/pkg-info.mk
DESCRIPTION: debian/DESCRIPTION.in
	sed -e "s/@VERSION@/$(DEB_VERSION_UPSTREAM)/" \
	    -e "s/@DATE@/$(shell date -u -I -d@$(SOURCE_DATE_EPOCH))/" $< > $@

override_dh_dwz:
# avoid the following:
# dwz: ./dwz.c:12035: adjust_exprloc: Assertion `refd != NULL &&
#   !refd->die_remove' failed.

override_dh_octave_substvar:
	dh_octave_substvar -poctave-phclab

override_dh_clean:
	dh_clean -Xbak

execute_after_dh_auto_clean:
	$(MAKE) -C src/Objects clean
	$(MAKE) -C src/Python/PHCpy3/doc clean
	$(MAKE) -C src/doc clean
	dh_auto_clean --buildsystem=octave || true