#!/usr/bin/make -f
export DH_VERBOSE=1
include /usr/share/dpkg/default.mk
export PYBUILD_NAME = nipy
export PYBUILD_TEST_ARGS=--pyargs nipy
export DEB_BUILD_MAINT_OPTIONS = hardening=+all
export NIPY_EXTERNAL_LAPACK=1

# stop matplotlib from thinking it should display plots
export MPLBACKEND=Agg

PYVER = $(shell py3versions -vd)
DESTDIR = $(CURDIR)/debian/python3-$(PYBUILD_NAME)
DISTDIR = $(DESTDIR)/usr/lib/python3/dist-packages

# Mega rule
%:
	dh $@ --buildsystem=pybuild --with=sphinxdoc

manpages:
	@echo "I: generating manpages"
	set -e \
	; mkdir -p $(CURDIR)/build/manpages \
	; cd $(DESTDIR)/usr/bin/ \
	; for f in * \
	; do descr=$$( \
		grep -h -e "^ *'''" -e 'DESCRIP =' $$f \
		| sed -e "s,.*' *\([^'][^']*\)'.*,\1,g" \
		| head -n 1 \
	     ) \
	;    PYTHONPATH=../ \
	     help2man -n "$${descr}" \
		--no-discard-stderr \
		--no-info \
		--version-string "$(DEB_VERSION_UPSTREAM)" \
		"python3 ./$$f" \
	     >| ../../../../build/manpages/$$f.1 \
	; done

execute_after_dh_auto_build-indep:
ifeq (,$(filter nodoc,$(DEB_BUILD_OPTIONS)))
	# Generate documentation
	PYTHONPATH=$$( \
		pybuild --print build_dir \
			--interpreter python$(PYVER) \
			--pyver $(PYVER) \
	) \
	  http_proxy='127.0.0.1:9' \
	  PATH=$(CURDIR)/debian/tmp/usr/bin/:$$PATH \
	  HOME=$(CURDIR)/build \
	  $(MAKE) -C doc html PYTHON=python$(PYVER)
	# Link in the local coy of mathjax
	ln -sf /usr/share/javascript/mathjax/ doc/build/html/_static/mathjax
endif

override_dh_install:
	@ echo 'I: Move libraries into the python3-nipy-lib packages'
	( cd $(DESTDIR) \
	  && find . -iname *.so \
	     | while read so \
	       ; do d=../python3-nipy-lib/$$(dirname $$so) \
	       ;    mkdir -p $$d \
	       ;    echo "Moving $$so under $$d" \
	       ;    mv $$so $$d \
	       ; done \
	)
	dh_install
	@ echo 'I: Assure versioned dependency on NumPy'
	dh_numpy3
	-rm debian/python-nipy-doc/usr/share/javascript/underscore/underscore.js

override_dh_python3:
	dh_python3 --shebang=/usr/bin/python3
	rm -vf $(DISTDIR)/nipy/algorithms/statistics/models/LICENSE.txt

## immediately usable documentation and exemplar scripts/data
override_dh_compress:
	@ echo 'I: Avoiding compression of what should not be compressed'
	dh_compress -X.py -X.html -X.pdf -X.css -X.jpg -X.txt -X.js -X.json -X.rtc -Xobjects.inv

override_dh_installman: manpages
	# FIXME: in their current state, manpages are useless, so are disabled.
	#dh_installman -ppython3-nipy build/manpages/*.1

override_dh_clean:
	@ echo 'I: Custom cleaning'
	rm -rf build nipy/neurospin/__config__.py
	$(MAKE) -C doc clean
	dh_clean

override_dh_auto_clean:
	# Do not force maintainers to install Build-Depends on local machine
	dh_auto_clean || rm -rf __pycache__ .pybuild
