#!/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


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)

# Override in 0.27.0 build - causes failures on mixed g++/clang environments
ENABLE_CLANG_TIDY:= Off

# OMP Doesn't appear to work on these archs
ARCH_NO_OMP:= riscv64 sparc64
ENABLE_OMP:=  $(if $(filter $(DEB_TARGET_ARCH), $(ARCH_NO_OMP)),Off,On)

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

# 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_test:
ifeq (,$(filter nocheck,$(DEB_BUILD_OPTIONS)))
	dh_auto_test || echo "Ignoring test failures in this build"
endif

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
