#!/usr/bin/make -f
# -*- makefile -*-
include /usr/share/dpkg/pkg-info.mk
include /usr/share/dpkg/architecture.mk

# Python versions
PY3DEF=$(shell py3versions -dv)
PY3VERS=$(shell py3versions -vr)

ifneq (,$(filter parallel=%,$(DEB_BUILD_OPTIONS)))
  NUMJOBS=$(patsubst parallel=%,%,$(filter parallel=%,$(DEB_BUILD_OPTIONS)))
  RUNTESTSOPTS=--shard_count=$(NUMJOBS)
endif

# In case matplotlib or anything else inquires
export HOME=$(CURDIR)/build
export MPLCONFIGDIR=$(CURDIR)/build

%:
	dh $@ --with python3 --buildsystem pybuild

override_dh_installman-arch: build/cython.1
	dh_installman -a

build/cython.1:
	: # Generate a manpage using help2man
	PYTHONPATH=`/bin/ls -d $(CURDIR)/build/lib.*-$(PY3DEF)` \
	  help2man --no-info --no-discard-stderr \
		-n "compile Cython code (.pyx) into C to build a Python extension" \
		bin/cython >| build/cython.1
	: # Verify that manpage generated nicely -- no Errors reported
	grep -q 'ImportError:' build/cython.1 && exit 1 || :

override_dh_install-indep:
	dh_install -i

override_dh_install-arch:
	dh_install -a

	: # fix shebang
	sed -i -e '1 s,#!.*python.*,#!/usr/bin/python3,' debian/cython3/usr/bin/*

	# add debian version to watermark of generated files
	sed -i -e "s/ on / (Debian $(DEB_VERSION)) on /" \
	  debian/cython3/usr/lib/python3*/dist-packages/Cython/Compiler/Version.py


override_dh_installdocs:
	: # Build Documentation
ifeq (,$(filter nodoc,$(DEB_BUILD_OPTIONS)))
ifneq (,$(findstring -a,$(DH_INTERNAL_OPTIONS)))
	: # not building documentation in -a
	: # just faking having documentation so that dh-installdocs doesn't fail
	mkdir -p docs/build/html
else
	make -C docs html
	: # Use jquery/underscore from Debian package, so prune shipped one
	-rm docs/build/html/_static/jquery.js docs/build/html/_static/underscore.js
endif
endif
	dh_installdocs --package=cython3 --link-doc=cython3 debian/upstream
	dh_installdocs --package=cython-doc debian/upstream


override_dh_installchangelogs:
	dh_installchangelogs --all CHANGES.rst


override_dh_auto_test:
ifeq (,$(filter nocheck,$(DEB_BUILD_OPTIONS))$(filter sparc64,$(DEB_HOST_ARCH)))
	set -e; for P in $(PY3VERS); do \
	 echo =============== $$P start ===============; \
	 if PYTHONPATH=`/bin/ls -d $(CURDIR)/build/lib.*-$$P` \
	  /usr/bin/python$$P runtests.py $(RUNTESTSOPTS) \
            --no-refnanny -v -v \
	    --exclude="(parallel|Debugger|annotate_html|numpy_test)" \
	    --work-dir=build/work-dir 2>&1; \
	 then \
	   echo =============== $$P done ===============; \
	 else \
	   echo "=============== $$P done (FAILURES IGNORED) ==============="; \
	 fi; \
	done
endif

override_dh_strip:
	dh_strip --dbgsym-migration='cython3-dbg (<< 0.29.36-1~)'

override_dh_auto_clean:
	make clean
	rm -rf Cython.egg-info docs/build
	rm -rf .pybuild
	find -name "*.py[oc]" -type f -delete
