#!/usr/bin/make -f

export DH_VERBOSE=1

# The magic debhelper  rule
%:
	dh $@ --buildsystem=cmake --with=python3

DEB_HOST_MULTIARCH ?= $(shell dpkg-architecture -qDEB_HOST_MULTIARCH)
AUTOGENERATED:= libodb-api-0d.install libodb-api-dev.install libodb-api-dev.links
LIBDIR:=/usr/lib/${DEB_HOST_MULTIARCH}
DESTDIR:=$(shell pwd)/debian/tmp

CMAKE_DIR_ECKIT:=debian/tmp/usr/share/eckit/cmake
CMAKE_DIR_ODBAPI:=debian/tmp/usr/share/odb_api/cmake
INC_DIR:=debian/tmp/usr/include

CMAKE_CFLAGS:= \
		-DCMAKE_BUILD_TYPE=Release \
		-DDISABLE_OS_CHECK=ON \
		-DBUILD_SHARED_LIBS=ON \
		-DENABLE_EIGEN=ON \
		-DENABLE_NETCDF=ON \
		-DENABLE_FORTRAN=ON \
		-DENABLE_PYTHON=ON \
		-DENABLE_VIENNACL=ON \
		-DPYTHON_EXECUTABLE=/usr/bin/python3 

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

override_dh_auto_configure:
	for f in ${AUTOGENERATED} ; do \
		sed -e 's%@ARCH@%${DEB_HOST_MULTIARCH}%g' < debian/$$f.in  > debian/$$f ; \
	done
	dh_auto_configure --  ${CMAKE_CFLAGS}

override_dh_auto_test:
	@echo "Skipping tests; need to disable downloads"
	# dh_auto_test ||  @echo "Ignoring test failures" 

override_dh_auto_install:
	dh_auto_install	
	for d in debian/tmp/usr/bin/* ; do \
		( chrpath -d $$d || echo "Ignoring non-ELF file errors") ; done
	chrpath -d debian/tmp/usr/lib/*.0d
	# Fix broken paths 
	cat ${CMAKE_DIR_ECKIT}/eckit-targets-release.cmake | \
		sed -e 's%$${_IMPORT_PREFIX}/bin%/usr/bin%' | \
		sed -e 	's%$${_IMPORT_PREFIX}/lib%$(LIBDIR)%' > ${CMAKE_DIR_ECKIT}/tmp
	mv ${CMAKE_DIR_ECKIT}/tmp ${CMAKE_DIR_ECKIT}/eckit-targets-release.cmake
	cat ${CMAKE_DIR_ODBAPI}/odb_api-targets-release.cmake | \
		sed -e 's%$${_IMPORT_PREFIX}/bin%/usr/bin%' | \
		sed -e 's%"/usr/bin/odb"%"/usr/bin/ecmwf_odb"%' | \
		sed -e 	's%$${_IMPORT_PREFIX}/lib%$(LIBDIR)%' > ${CMAKE_DIR_ODBAPI}/tmp
	mv ${CMAKE_DIR_ODBAPI}/tmp ${CMAKE_DIR_ODBAPI}/odb_api-targets-release.cmake
	# Sanitise paths for bit reproducibility
	cat ${CMAKE_DIR_ODBAPI}/odb_api-config.cmake | \
		sed -e 's%${CURDIR}%/build/odb-api%g' > ${CMAKE_DIR_ODBAPI}/tmp
	mv ${CMAKE_DIR_ODBAPI}/tmp ${CMAKE_DIR_ODBAPI}/odb_api-config.cmake
	# Delete files that break reproducibility, and refs from include files
	rm -f ${INC_DIR}/odb_api/odb_api_ecbuild_config.h \
		${INC_DIR}/eckit/eckit_ecbuild_config.h   \
		${INC_DIR}/metkit/metkit_ecbuild_config.h 
	grep -v odb_api_ecbuild_config.h ${INC_DIR}/odb_api/odb_api_config.h | \
		grep -v ODB_API_BINARY_DIR > ${INC_DIR}/tmp
	mv ${INC_DIR}/tmp ${INC_DIR}/odb_api/odb_api_config.h
	grep -v eckit_ecbuild_config.h ${INC_DIR}/eckit/eckit_config.h | \
		grep -v ECKIT_BUILD_DIR > ${INC_DIR}/tmp
	mv ${INC_DIR}/tmp ${INC_DIR}/eckit/eckit_config.h
	grep -v metkit_ecbuildconfig.h ${INC_DIR}/metkit/metkit_config.h > ${INC_DIR}/tmp
	mv ${INC_DIR}/tmp ${INC_DIR}/metkit/metkit_config.h
	# Avoid conflict with different odb ( #880890) 
	mv debian/tmp/usr/bin/odb	debian/tmp/usr/bin/ecmwf_odb

