#!/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)/$(LIBDIR)/cmake/atlas


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)
ENABLE_FORTRAN:=$(if $(filter $(DEB_TARGET_ARCH), $(ARCH_32BIT)),Off,On)

FCKIT_ARCHS:= amd64 arm64 mips64el ppc64el s390x
ENABLE_CLANG_TIDY:= $(if $(filter $(DEB_TARGET_ARCH), $(FCKIT_ARCHS)),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=$(ENABLE_FORTRAN) \
	-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:
	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

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)/$(LIBDIR)/*.so*
	# Fix broken paths
	sed -i -e 's%$${CURDIR}%/build/atlas-ecmwf%g' $(CMAKE_DIR)/atlas-config.cmake
	sed -i -e 's%$${CURDIR}%/build/atlas-ecmwf%g' $(CMAKE_DIR)/atlas-targets.cmake
	sed -i -e 's%/cmake/atlas"%/cmake/atlas_ecmwf"%g' $(CMAKE_DIR)/atlas-config.cmake
	sed -i -e 's%/cmake/atlas"%/cmake/atlas_ecmwf"%g' $(CMAKE_DIR)/atlas-targets.cmake
	sed -i -e 's%include/atlas%include/${DEB_HOST_MULTIARCH}/atlas%g'  $(CMAKE_DIR)/atlas-targets.cmake
