#!/usr/bin/make -f

# DH_VERBOSE := 1
export LC_ALL=C.UTF-8
export AUTOHEADER=true  # confusingly, this skips autoheader

export DEB_BUILD_MAINT_OPTIONS=hardening=+all
DPKG_EXPORT_BUILDFLAGS = 1
include /usr/share/dpkg/buildflags.mk

include /usr/share/dpkg/default.mk

EASEL_VERSION   = 0.49.0
EASEL_SOVERSION = 0
MULTIARCH      := $(shell dpkg-architecture -qDEB_HOST_MULTIARCH)

# the miniapps link and run against the shared library built in this tree
export LD_LIBRARY_PATH=$(CURDIR)

%:
	dh $@

override_dh_auto_configure:
	dh_auto_configure -- --enable-mpi --enable-pic CC=mpicc # --with-gsl

override_dh_auto_build:
	chmod a+x devkit/cexcerpt
	$(MAKE) libeasel.a
	# build libeasel.so first, so that dh_auto_build links the miniapps
	# against it (ld prefers the shared library in -L.. over libeasel.a)
	mpicc $(CPPFLAGS) $(CFLAGS) $(LDFLAGS) -shared \
		-Wl,-soname,libeasel.so.$(EASEL_SOVERSION) \
		-o libeasel.so.$(EASEL_VERSION) \
		-Wl,--whole-archive libeasel.a -Wl,--no-whole-archive -lm -lpthread
	ln -sf libeasel.so.$(EASEL_VERSION) libeasel.so.$(EASEL_SOVERSION)
	ln -sf libeasel.so.$(EASEL_SOVERSION) libeasel.so
	dh_auto_build
	$(MAKE) -C documentation pdf || { grep -n -A5 '^!' documentation/latex.log; exit 1; }
	chmod a-x devkit/cexcerpt

override_dh_auto_install:
	dh_auto_install
	install -d debian/tmp/usr/lib/$(MULTIARCH)/pkgconfig debian/tmp/usr/include/easel
	install -m644 libeasel.so.$(EASEL_VERSION) debian/tmp/usr/lib/$(MULTIARCH)/
	install -m644 libeasel.a debian/tmp/usr/lib/$(MULTIARCH)/
	ln -sf libeasel.so.$(EASEL_VERSION) debian/tmp/usr/lib/$(MULTIARCH)/libeasel.so.$(EASEL_SOVERSION)
	ln -sf libeasel.so.$(EASEL_SOVERSION) debian/tmp/usr/lib/$(MULTIARCH)/libeasel.so
	install -m644 *.h debian/tmp/usr/include/easel/
	sed -e 's/@VERSION@/$(EASEL_VERSION)/' \
	    -e 's|@LIBDIR@|/usr/lib/$(MULTIARCH)|' \
	    debian/easel.pc.in > debian/tmp/usr/lib/$(MULTIARCH)/pkgconfig/easel.pc
	d-shlibmove --commit --multiarch --devunversioned --exclude-la \
	    --movedev debian/tmp/usr/include/easel usr/include \
	    --movedev debian/tmp/usr/lib/$(MULTIARCH)/pkgconfig/easel.pc usr/lib/$(MULTIARCH)/pkgconfig \
	    --override 's/\(libmpi40\|libopen_mpi40\|libmpich12\)-dev/mpi-default-dev/' \
	    debian/tmp/usr/lib/$(MULTIARCH)/libeasel.so

