#!/usr/bin/make -f
# -*- makefile -*-

# get octave paths (have to build-depend on octave-headers)
include /usr/share/octave/debian/defs.make
# same for Matlab
include /usr/share/matlab/debian/defs.make

# on older systems such as 16.04 PIE is not enabled by  default and
# configure them fails # to link
DISABLE_HARDENING_OPTS=$(shell  g++ -v 2>&1 | grep -q -e --enable-default-pie || echo ",-pie") 
export DEB_BUILD_MAINT_OPTIONS=hardening=+all$(DISABLE_HARDENING_OPTS)

# To avoid --match=native since wouldn't be supported on some platforms
export CPP_MARCH=

DEB_HOST_ARCH=$(shell dpkg-architecture -qDEB_HOST_ARCH)
# guarantee the same precision on x86 platforms for tests
ifneq (,$(findstring z$(DEB_HOST_ARCH)z,zamd64z zi386z))
    CFLAGS+=-mmmx -msse -msse2 -mfpmath=sse
endif

# To prevent any online interactions
export  http_proxy=http://127.0.0.1:9/
export  https_proxy=http://127.0.0.1:9/

#
# Upstream uses a custom set of configure/build scripts to build the project
#

# one ring to rule them all ...
%:
	dh $@

override_dh_auto_configure:
	./configure -openmp # -debug

override_dh_auto_build:
	./build -verbose

override_dh_install:
	dh_install
	# .pyc files get generated, so we remove all the .pyc/.pyo etc
	-find debian -iname *.py? -delete

override_dh_auto_test:
	./run_tests || { cat testing.log; exit 1; }

override_dh_link:
	cp debian/mrtrix3.links.in debian/mrtrix3.links
	: # Generate symlinks for all the mr* commands
	for f in debian/mrtrix3/usr/lib/mrtrix3/bin/mrview; do \
		bn=$$(basename $$f); \
		echo "usr/lib/mrtrix3/bin/$$bn usr/bin/$$bn" >> debian/mrtrix3.links; \
	    echo "/usr/share/man/man1/mrtrix.1.gz /usr/share/man/man1/$$bn.1.gz" >> debian/mrtrix3.links; \
	done
	echo "/usr/share/mrtrix3/matlab $(MATLAB_MDIR)/mrtrix" >> debian/mrtrix3.links
	echo "/usr/share/mrtrix3/matlab $(MDIR)/mrtrix" >> debian/mrtrix3.links
	dh_link

# we want immediately useable docs and example data, they are in a dedicated
# package already
override_dh_compress:
	dh_compress -X.html

override_dh_clean:
	./build clean
	find . -name '*.pyc' -delete
	-rm clean \
		config configure.log build.log \
		core/version.cpp lib/mrtrix3/_version.py src/exec_version.cpp
	dh_clean
	@rm -f debian/mrtrix.links

override_dh_shlibdeps:
	dh_shlibdeps -l $(CURDIR)/lib
