#!/usr/bin/make -f

# Uncomment this to turn on verbose mode.
export DH_VERBOSE=1

# magic debhelper rule
%:
	dh $@ --buildsystem=cmake

include /usr/share/dpkg/architecture.mk

ifeq ($(shell dpkg-architecture -qDEB_TARGET_ARCH_BITS), 64)
    FPZIP:= -DSILO_ENABLE_FPZIP=1
else
    FPZIP:= -DSILO_ENABLE_FPZIP=0
endif

# export CONFIG_SHELL=/bin/sh

PY3VERS:= $(shell py3versions -s)
PY3EXTRA:= $(filter-out $(shell py3versions -d),$(PY3VERS))
PYABI:=$(shell python3  -c "import sysconfig; print(sysconfig.get_config_var('SOABI'))")
LIBDIR:=/usr/lib/$(DEB_HOST_MULTIARCH)

DO_MPI=$(shell  pkg-config --exists hdf5-mpi 2> /dev/null; echo $$?)
ifeq ($(DO_MPI),0)
	HDF5_INC:=$(shell pkg-config --cflags hdf5-mpi) 
	HDF5_LIB:=$(shell pkg-config --libs hdf5-mpi) 
else
	HDF5_INC:=$(shell pkg-config --cflags hdf5-serial ) 
	HDF5_LIB:=$(shell pkg-config --libs hdf5-mpi ) 
endif

CMAKE_ARGS:= \
		-DCMAKE_SKIP_RPATH=On \
		-DSILO_ENABLE_HDF5=On  \
		-DSILO_ENABLE_SILEX=On \
		-DSILO_ENABLE_INSTALL_LITE_HEADERS=On \
		-DSILO_ENABLE_PYTHON_MODULE=On \
		$(FPZIP) \
		-DCMAKE_C_FLAGS="$(CFLAGS) $(HDF5_INC) -fPIC " \
		-DCMAKE_CXX_FLAGSS="$(CXXFLAGS) -$(HDF5_INC) -fPIC " \
		LDFLAGS="$(LDFLAGS) -L$(HDF5_LIB) " 

override_dh_auto_configure:
	dh_auto_configure -- $(CMAKE_ARGS) -DPython_EXECUTABLE=/usr/bin/python3
	set -e; for p in $(PY3EXTRA); do \
		dh_auto_configure -Bbuild-$$p -- $(CMAKE_ARGS) -DPython_EXECUTABLE=/usr/bin/$$p; \
	done

execute_after_dh_auto_build:
	set -e; for p in $(PY3EXTRA); do dh_auto_build -Bbuild-$$p -- SiloPy; done

execute_after_dh_auto_clean:
	rm -rf $(addprefix build-,$(PY3EXTRA))

execute_before_dh_install:
	# move the python modules to where dh_python* will spot them ...
	mkdir -p  debian/tmp/usr/lib/python3/dist-packages
	mv debian/tmp/$(LIBDIR)/Silo.so debian/tmp/usr/lib/python3/dist-packages/Silo.$(PYABI).so
	set -e; for p in $(PY3EXTRA); do \
		cp build-$$p/lib/$(DEB_HOST_MULTIARCH)/Silo.so debian/tmp/usr/lib/python3/dist-packages/Silo.$$($$p -c "import sysconfig; print(sysconfig.get_config_var('SOABI'))").so; \
	done
	mv debian/tmp/usr/bin/s2ex.py debian/tmp/usr/bin/s2ex
