#!/usr/bin/make -f

export DH_VERBOSE=1

include /usr/share/dpkg/pkg-info.mk
DEB_HOST_MULTIARCH ?= $(shell dpkg-architecture -qDEB_HOST_MULTIARCH)
LIBDIR:=/usr/lib/$(DEB_HOST_MULTIARCH)
INCDIR:=/usr/include/$(DEB_HOST_MULTIARCH)
INSTDIR:=$(CURDIR)/debian/tmp
CMAKE_DIR:=$(INSTDIR)/usr/lib/cmake/atlas

AUTOGENERATED:=libatlas-ecmwf-dev.install libatlas-ecmwf-0.install \
		libatlas-ecmwf-dev.links  libatlas-ecmwf-0.links

FC:=$(shell basename $(shell readlink -f /usr/bin/f95))
FMODDIR:=/usr/lib/$(shell dpkg-architecture -qDEB_HOST_MULTIARCH)/fortran/$(FC)

DEB_CFLAGS_MAINT_APPEND= -I$(CURDIR)/src -I$(CURDIR)/obj-$(DEB_HOST_MULTIARCH)/src
DEB_CXXFLAGS_MAINT_APPEND= -I$(CURDIR)/src -I$(CURDIR)/obj-$(DEB_HOST_MULTIARCH)/src
DEB_FFLAGS_MAINT_APPEND= -I$(FMODDIR)
include /usr/share/dpkg/buildflags.mk

# Fixes for 32-bit archss
ARCH_32BIT:=   i386 armel armhf mipsel hppa hurd-i386 m68k powerpc sh4 x32
ENABLE_32BIT:= $(if $(filter $(DEB_TARGET_ARCH), $(ARCH_32BIT)),On,Off)

# Strange bug with omp.h headers and clang-tidy on some archs
ARCH_CLANG_TIDY_OFF:= s390x mipsel
ENABLE_CLANG_TIDY:= $(if $(filter $(DEB_TARGET_ARCH), $(ARCH_CLANG_TIDY_OFF)),Off,On)

BUILD_FLAGS = \
	-DENABLE_DOCS=On \
	-DENABLE_CLANG_TIDY=$(ENABLE_CLANG_TIDY) \
	-DENABLE_GRIDTOOLS_STORAGE=Off  \
	-DENABLE_ACC=Off \
	-DENABLE_FORTRAN=Off \
	-Datlas_FULL_INSTALL_CMAKE_DIR=$(LIBDIR)/cmake/atlas_ecmwf \
	-DENABLE_INIT_SNAN=On \
	-DENABLE_PROJ=On \
	-DENABLE_32_BIT_HOST=$(ENABLE_32BIT)

# Test suite requires 4 processors. Fake it
export OMPI_MCA_rmaps_base_oversubscribe=1

%:
	dh $@ --buildsystem=ecbuild

override_dh_auto_configure:
	for f in ${AUTOGENERATED} ; do \
                sed -e 's%@MULTIARCH@%${DEB_HOST_MULTIARCH}%g' < debian/$$f.in > debian/$$f ; \
                done
	dh_auto_configure -- ${BUILD_FLAGS} 
	#ln -s atlas_ecmwf_ecbuild_config.h obj-$(DEB_HOST_MULTIARCH)/src/atlas/atlas_ecbuild_config.h

override_dh_auto_clean:
	dh_auto_clean
	rm -f cmake/FindLatex.cmake
	rm -f $(patsubst %, debian/%, ${AUTOGENERATED})

override_dh_auto_test:
	@echo Tests disabled in this release

override_dh_auto_install:
	dh_auto_install
	mkdir -p $(INSTDIR)/$(LIBDIR)/pkgconfig
	chrpath -d $(INSTDIR)/usr/bin/*
	chrpath -d $(INSTDIR)/usr/lib/*.so*
	# Fix broken paths
	for d in \
		$(CMAKE_DIR)/atlas-config.cmake \
		$(CMAKE_DIR)/atlas-targets.cmake \
		$(CMAKE_DIR)/atlas-targets-release.cmake \
		$(CMAKE_DIR)/atlas-targets-none.cmake ; do \
		cat $$d | \
			sed -e 's%$${_IMPORT_PREFIX}/include%$(INCDIR)%g' | \
			sed -e 's%$${_IMPORT_PREFIX}/lib%$(LIBDIR)%g' | \
			sed -e 's%$${_IMPORT_PREFIX}/bin%/usr/bin%g' | \
			sed -e 's%$${PACKAGE_PREFIX_DIR}/lib/cmake/atlas%$(LIBDIR)/cmake/atlas_ecmwf%g' | \
			sed -e 's%"/usr/lib/cmake/atlas"%"/usr"%'  \
		> $(CMAKE_DIR)/tmp ; \
		mv $(CMAKE_DIR)/tmp $$d ; \
		done

