#!/usr/bin/make -f
BUILDDIR = $(CURDIR)/debian/build
DEB_HOST_MULTIARCH ?= $(shell dpkg-architecture -qDEB_HOST_MULTIARCH)
DEB_BUILD_PARALLEL ?= $(shell guess_concurrency --require-mem 8G,6G)
PY3VERS := $(shell py3versions -sv)
PY3VER_DEFAULT := $(shell py3versions -dv)

CMAKE_FLAGS = \
      -DCOLLADA_SUPPORT=Off \
      -DBUILD_SHARED_LIBS=On \
      -DHDF5_SUPPORT=Off \
      -DCGAL_INCLUDE_DIR=/usr/include \
      -DGMP_INCLUDE_DIR=/usr/include \
      -DMPFR_INCLUDE_DIR=/usr/include \
      -DPCRE_LIBRARY_DIR=/usr/lib/$(DEB_HOST_MULTIARCH) \
      -DGMP_LIBRARY_DIR=/usr/lib/$(DEB_HOST_MULTIARCH) \
      -DMPFR_LIBRARY_DIR=/usr/lib/$(DEB_HOST_MULTIARCH) \
      -DJSON_INCLUDE_DIR=/usr/include \
      -DEIGEN_DIR=/usr/include/eigen3 \
      -DCMAKE_SKIP_INSTALL_RPATH=ON \
      -DBUILD_EXAMPLES=OFF

%:
	dh $@ --buildsystem=cmake --sourcedirectory=cmake --builddirectory=$(BUILDDIR)/$(PY3VER_DEFAULT) --max-parallel=$(DEB_BUILD_PARALLEL)

override_dh_auto_configure:
	set -e; for pyver in $(PY3VERS); do \
		dh_auto_configure \
		    --sourcedirectory=cmake \
		    --builddirectory=$(BUILDDIR)/$$pyver \
		    -- $(CMAKE_FLAGS) \
		    -DPYTHON_INCLUDE_DIR=/usr/include/python$$pyver \
		    -DPYTHON_LIBRARY=/usr/lib/$(DEB_HOST_MULTIARCH)/libpython$$pyver.so; \
	done

override_dh_auto_build:
	set -e; for pyver in $(PY3VERS); do \
		dh_auto_build --builddirectory=$(BUILDDIR)/$$pyver --max-parallel=$(DEB_BUILD_PARALLEL); \
	done

override_dh_auto_test:
	set -e; for pyver in $(PY3VERS); do \
		dh_auto_test --builddirectory=$(BUILDDIR)/$$pyver --max-parallel=$(DEB_BUILD_PARALLEL); \
	done

override_dh_auto_install:
	dh_auto_install --builddirectory=$(BUILDDIR)/$(PY3VER_DEFAULT)
	# Install the other Python versions through CMake as well, so that the
	# build-tree RUNPATH of their wrapper module is stripped (#1138596).
	set -e; for pyver in $(PY3VERS); do \
		if [ "$$pyver" != "$(PY3VER_DEFAULT)" ]; then \
			dh_auto_install --builddirectory=$(BUILDDIR)/$$pyver \
			    --destdir=$(BUILDDIR)/install-$$pyver; \
			find $(BUILDDIR)/install-$$pyver -name "_ifcopenshell_wrapper.cpython-*.so" \
			    -exec install -m 644 {} \
			    $(CURDIR)/debian/tmp/usr/lib/python3/dist-packages/ifcopenshell/ \; ; \
		fi; \
	done
	# Refuse to ship any ELF object with a RUNPATH/RPATH (#1138596).
	set -e; bad=$$(find debian/tmp -type f \( -name '*.so*' -o -path '*/bin/*' \) \
	    -exec sh -c 'readelf -d "$$1" 2>/dev/null | grep -qE "\((RUNPATH|RPATH)\)" && echo "$$1"' _ {} \;); \
	if [ -n "$$bad" ]; then echo "RUNPATH/RPATH found in:"; echo "$$bad"; exit 1; fi

override_dh_dwz:

execute_after_dh_clean:
	rm -rf $(BUILDDIR)
