#!/usr/bin/make -f

export DH_VERBOSE=1

include /usr/share/debhelper/dh-fortran/fortran-support.mk

DESTDIR:=$(CURDIR)/debian/tmp/
DEB_HOST_MULTIARCH ?= $(shell dpkg-architecture -qDEB_HOST_MULTIARCH)
LIBDIR:=/usr/lib/$(DEB_HOST_MULTIARCH)
INCDIR:=/usr/include/$(DEB_HOST_MULTIARCH)

# To enable all, uncomment following line
export DEB_BUILD_MAINT_OPTIONS:= hardening=+all
export DEB_CFLAGS_MAINT_APPEND:= -Wall -pedantic
export DEB_CXXFLAGS_MAINT_APPEND:= -Wall -pedantic
export DEB_FCFLAGS_MAINT_APPEND:= -Wall
export DEB_FFLAGS_MAINT_APPEND:= -Wall
LDFLAGS:=$(shell dpkg-buildflags --get LDFLAGS) -Wl,--no-as-needed -lgfortran -Wl,--as-needed

FCFLAGS=$(FFLAGS)

export FC=gfortran
export OMPI_FC=gfortran
export MPIF77=mpif77
export MPIF90=mpif90
export FFLAGS FCFLAGS
SHLIB=libpnetcdf.so.0d

# The magic debhelper  rule
%:
	dh $@ 

override_dh_auto_clean:
	rm -rf build-*

override_dh_auto_configure:
	dh_auto_configure  --builddirectory=build-static
		OMPI_CFLAGS=" $(CFLAGS)"   OMPI_CXXFLAGS="$(CXXFLAGS)" \
		OMPI_FCFLAGS="$(FCFLAGS)" OMPI_FFLAGS="$(FFLAGS)" \
		OMPI_LDFLAGS="$(LDFLAGS)"  \
		OMPI_FC=gfortran FC=gfortran
	dh_auto_configure  --builddirectory=build-shared -- \
		CFLAGS=" $(CFLAGS) -fPIC -g"  CXXFLAGS="$(CXXFLAGS) -fPIC -g" \
		FCFLAGS="$(FCFLAGS) -fPIC -g" FFLAGS="$(FFLAGS) -fPIC -g" \
		LDFLAGS="$(LDFLAGS) -g" \
		OMPI_CFLAGS=" $(CFLAGS) -fPIC -g"  OMPI_CXXFLAGS="$(CXXFLAGS) -fPIC -g" \
		OMPI_FCFLAGS="$(FCFLAGS) -fPIC -g" OMPI_FFLAGS="$(FFLAGS) -fPIC -g" \
		OMPI_LDFLAGS="$(LDFLAGS) -g"  \
		OMPI_FC=gfortran FC=gfortran

override_dh_auto_build:
	$(MAKE) -C build-static
	$(MAKE) -C build-shared
	( cd build-shared/src/libs && \
		mpicxx -shared -o $(SHLIB) -Wl,--soname -Wl,$(SHLIB) $(LDFLAGS) \
		-Wl,--whole-archive .libs/libpnetcdf.a -Wl,--no-whole-archive  )

override_dh_auto_test:
	( cd build-static/test && $(MAKE) check ) || true
	( cd build-shared/test && $(MAKE) check ) || true

override_dh_auto_install:
	$(MAKE) -C build-static install DESTDIR=$(DESTDIR)
	find $(DESTDIR) -name '*.la' -delete
	chrpath -d debian/tmp/usr/lib/*/*.so.6.*
	for d in cdfdiff ncmpidiff ncmpidump ncmpigen ncoffsets ncvalidator pnetcdf_version  ;do \
		chrpath -d debian/tmp/usr/bin/$$d ; done
