#!/usr/bin/make -f
# -*- mode: makefile; coding: utf-8 -*-

PACKAGE2_NAME = python-skimage
PACKAGE3_NAME = python3-skimage
PKG_TMP = $(CURDIR)/debian/tmp

# don't optimize pngs, palette changes break tests and documented examples
export NO_PNG_PKG_MANGLE=1

PY3VER = $(shell py3versions  -vd)

export DEB_BUILD_MAINT_OPTIONS := hardening=+all

# upstream relies on signed chars
export DEB_CFLAGS_MAINT_APPEND := -fsigned-char
export DEB_LDFLAGS_MAINT_APPEND := -Wl,--as-needed

ifneq (,$(filter parallel=%,$(DEB_BUILD_OPTIONS)))
  JOBS = $(patsubst parallel=%,%,$(filter parallel=%,$(DEB_BUILD_OPTIONS)))
else
  JOBS = 1
endif

# Assure Agg backend for matplotlib to avoid any possible complication
export MPLBACKEND := Agg


%:
	dh $@ --with python2,python3,sphinxdoc --buildsystem pybuild

override_dh_clean-arch:
	rm -rf .pytest_cache scikit_image.egg-info
	dh_clean

override_dh_auto_clean-indep:
	+$(MAKE) -C doc clean
	rm -f doc/source/_static/random.js

# Test data and plugin ini not copied to .pybuild -- manually link for them
override_dh_auto_test:
	for i in .pybuild/cpython*/build/skimage; do \
		cp skimage/io/_plugins/*.ini $$i/io/_plugins/; \
		rm -rf $$i/data || true; \
		ln -sf ../../../../skimage/data $$i; \
		for module in $$(find skimage ! -path '*/data/*' -name tests | cut -sd / -f 2-); do \
			rm -rf $$i/$$module || true; \
			ln -sf $(CURDIR)/skimage/$$module $$i/$${module%/*}/; \
		done; \
	done
	xvfb-run -a dh_auto_test

override_dh_auto_install-arch:
	dh_auto_install
	# cleanup python3 cache for python2 (in data dir, since symlinked)
	-find $(PKG_TMP)/usr/lib/python2* -name "__pycache__" -exec rm -r {} +

# Build docs during install
# Tricky -- doc building depends on python module!
override_dh_auto_install-indep:
ifeq (,$(filter nodoc,$(DEB_BUILD_OPTIONS)))
	# Build Documentation
	# hotfix SPHINXBUILD -- remove in next release
	+\
		PYTHONPATH=$(CURDIR)/.pybuild/cpython3_$(PY3VER)/build:$$(python3 -c 'import sys;print(":".join(sys.path))') \
		PYTHON=python$(PY3VER) \
		SPHINXBUILD="python$(PY3VER) -m sphinx" \
		SPHINXOPTS="-j $(JOBS) -D mathjax_path=MathJax.js" \
		$(MAKE) -C doc html
endif

## remove .so libraries from main package, and call dh_numpy*
_dh_python%:
	-find debian/$(PACKAGE$*_NAME)/usr/lib -name "*.so" -delete

	dh_numpy$(*:2=) -p$(PACKAGE$*_NAME)-lib
	dh_python$*

override_dh_python2: _dh_python2
override_dh_python3: _dh_python3

## immediately useable documentation and exemplar scripts/data
override_dh_compress:
	dh_compress -X.py -X.html -X.pdf -X.css -X.jpg -X.txt -X.js -X.json -X.rtc

override_dh_sphinxdoc:
ifeq (,$(findstring nodoc,$(DEB_BUILD_OPTIONS)))
ifneq (,$(findstring -a,$(DH_INTERNAL_OPTIONS)))
	# no documentation in -a -- surprised that sphinxdoc doesn't know that
else
	dh_sphinxdoc -ppython-skimage-doc -XMathJax.js
endif
endif

override_dh_installdocs:
	dh_installdocs -A CONTRIBUTORS.txt README.md CONTRIBUTING.txt
