#!/usr/bin/make -f

export DH_VERBOSE=1


DPKG_EXPORT_BUILDFLAGS = 1
include /usr/share/dpkg/buildflags.mk

DEB_HOST_MULTIARCH ?= $(shell dpkg-architecture -qDEB_HOST_MULTIARCH)
LIBDIR=/usr/lib/$(DEB_HOST_MULTIARCH)
AUTOGENERATED:= pmix-mca-params.conf
CFLAGS:=$(shell dpkg-buildflags --get CFLAGS)  -fPIC

PSM_ARCH= amd64 i386
UCX_ARCH= amd64 arm64 ppc64el
PSM2_ARCH= amd64 
PSM2:= $(if $(filter $(DEB_TARGET_ARCH),$(PSM2_ARCH)), --with-psm2, )
UCX:=  $(if $(filter $(DEB_TARGET_ARCH),$(UCX_ARCH)), --with-ucx=/usr, )


ifneq (,$(filter $(DEB_HOST_ARCH), armel mipsel sh4 m68k ))
  export DEB_LDFLAGS_MAINT_APPEND += -Wl,--no-as-needed -latomic -Wl,--as-needed
endif

export LD_LIBRARY_PATH:=$(CURDIR)/debian/tmp/$(LIBDIR)/pmix2/lib:$(LD_LIBRARY_PATH)

# Do not embed build username or build system hostname, see README
export HOSTNAME=hostname
export USER=username

%:
	dh $@ 

BUILD_FLAGS:= \
	$(PSM2) \
	$(UCX) \
	--prefix=$(LIBDIR)/pmix2 \
	--libdir=$(LIBDIR)/pmix2/lib \
	--includedir=$(LIBDIR)/pmix2/include \
	--sysconfdir=$(LIBDIR)/pmix2/share \
	--datarootdir=$(LIBDIR)/pmix2/share \
	--with-curl \
	--with-zlib=/usr \
	--with-zlib-libdir=$(LIBDIR) \
	--with-jansson=/usr \
	--with-hwloc=/usr \
	--with-hwloc-libdir=$(LIBDIR) \
	--enable-python-bindings \
	$(if $(filter $(DEB_HOST_ARCH), i386),--disable-man-pages)

override_dh_auto_clean:
	dh_auto_clean
	rm -f $(patsubst %, debian/%, ${AUTOGENERATED})
	rm -rf debian/static-build debian/shared-build

override_dh_autoreconf:
	./autogen.pl --force
	for f in ${AUTOGENERATED} ; do \
                sed -e 's%@DEB_HOST_MULTIARCH@%${DEB_HOST_MULTIARCH}%g' < debian/$$f.in  > debian/$$f ; \
                done

override_dh_auto_configure:
	dh_auto_configure --builddirectory=debian/static-build -- $(BUILD_FLAGS) \
		--enable-static 
	dh_auto_configure --builddirectory=debian/shared-build -- $(BUILD_FLAGS) \
		--enable-shared

override_dh_auto_build:
	# Hack - build system doesn't work well with builddirs
	cp include/*.h debian/static-build/include
	cp include/*.h debian/shared-build/include
	cp debian/static-build/include/pmix_version.h include
	cp bindings/python/pmix.* debian/static-build/bindings/python
	cp bindings/python/pmix.* debian/shared-build/bindings/python
	dh_auto_build  --builddirectory=debian/static-build
	dh_auto_build  --builddirectory=debian/shared-build

override_dh_auto_install:
	dh_auto_install --builddirectory=debian/static-build
	dh_auto_install --builddirectory=debian/shared-build
	find debian/tmp -name '*.la' -delete
	chrpath -d debian/tmp/$(LIBDIR)/pmix2/bin/*
	chrpath -d debian/tmp/$(LIBDIR)/pmix2/lib/pmix/*.so

