#!/usr/bin/make -f

# Get version from changelog as well as lsb_release
# to compute unique build version (useful for repo mirroring systems doing file pooling)
PKG_VERSION  := $(shell dpkg-parsechangelog | grep -E '^Version:' | cut -d' ' -f2)
DIST_NAME    := $(shell lsb_release -si)
DIST_RELEASE := $(shell lsb_release -sc)
DIST_VERSION := $(shell lsb_release -sr)
PKG_VERSION_TAG := $(PKG_VERSION)+$(DIST_NAME).$(DIST_RELEASE).$(DIST_VERSION)

%:
	dh $@ --parallel

override_dh_auto_clean:
	dh_auto_clean
	rm -rf build
	rm -rf external

override_dh_auto_configure:
	# Configure two variantis, with or without Intel MKL proprietary lib
	dh_auto_configure --builddirectory=build/without-mkl
	scripts/prepare_mkl.sh
	# Will install the additional non-free Intel MKL libs in a private directory
	# CMake files says if MKLINC is known, MKL DNN path is set to MKLINC, but MKLINC goes to /usr/include
	dh_auto_configure --builddirectory=build/with-mkl -- -DCMAKE_INSTALL_RPATH=/usr/lib/libmkldnn0-nonfree-mkl -DMKLINC=False

override_dh_auto_build:
	dh_auto_build --builddirectory=build/without-mkl
	# Doxygen documentation
	$(MAKE) -C build/without-mkl doc
	dh_auto_build --builddirectory=build/with-mkl

override_dh_auto_test:
	dh_auto_test --builddirectory=build/without-mkl
	dh_auto_test --builddirectory=build/with-mkl

override_dh_auto_install:
	dh_auto_install --builddirectory=build/without-mkl --destdir=debian/tmp/without-mkl
	dh_auto_install --builddirectory=build/with-mkl --destdir=debian/tmp/with-mkl

override_dh_install:
	dh_install --sourcedir=debian/tmp/without-mkl \
	  -plibmkldnn0-free \
          -plibmkldnn-free-dev \
	  -plibmkldnn-docs
	dh_install --sourcedir=debian/tmp/with-mkl \
	  -plibmkldnn-nonfree-dev \
	  -plibmkldnn0-nonfree-mkl
	# ldconfig should handle this new folder
	mkdir -p debian/libmkldnn0-nonfree-mkl/etc/ld.so.conf.d
	echo "/usr/lib/libmkldnn0-nonfree-mkl" > debian/libmkldnn0-nonfree-mkl/etc/ld.so.conf.d/libmkldnn0-nonfree-mkl.conf
	# Mixing dev symlink and unversionned real libs asks for workarounds
	rm -f debian/libmkldnn0-nonfree-mkl/usr/lib/libmkldnn0-nonfree-mkl/libmkldnn.so

override_dh_installdocs:
	# Link all doc package to this one
	# Cant use dh_installdocs for linking because it will generate
	# broken dependencies, thanks to dh_gencontrol override below
	dh_installdocs -plibmkldnn-docs
	for package in `grep '^Package' debian/control | cut -d: -f2 | grep -v libmkldnn-docs`; do \
	  rm -rf debian/$${package}/usr/share/doc/$${package} && \
	  mkdir -p debian/$${package}/usr/share/doc/ && \
          ln -sf /usr/share/doc/libmkldnn-docs debian/$${package}/usr/share/doc/$${package}; \
	done

# Do not compress examples for easier building
override_dh_compress:
	dh_compress -Xusr/share/doc/libmkldnn-docs/examples

# Custom binary packages name using distro version
override_dh_gencontrol:
	dh_gencontrol -- -v"$(PKG_VERSION_TAG)" -Vcustom:Version="$(PKG_VERSION_TAG)"
