#!/usr/bin/make -f

export PYTHONWARNINGS=d
export PYTHONHASHSEED=random

export CFLAGS = $(shell dpkg-buildflags --get CFLAGS)
export CFLAGS_noopt = $(patsubst -O%,-O0,$(CFLAGS))
export CPPFLAGS = $(shell dpkg-buildflags --get CPPFLAGS)
export LDFLAGS = $(shell dpkg-buildflags --get LDFLAGS)

dawgdic_version = $(shell dpkg-query -Wf '$${Version}' libdawgdic-dev)

parallel = -P$(or $(patsubst parallel=%,%,$(filter parallel=%,$(DEB_BUILD_OPTIONS))),1)
python2 = $(shell pyversions -r)
python3 = $(shell py3versions -r)
python2d = $(addsuffix -dbg,$(python2))
python3d = $(addsuffix -dbg,$(python3))
python_all = $(python2) $(python2d) $(python3) $(python3d)
loop = echo -n $(1) | xargs $(2) -d ' ' -t -I {} env {} 

# clean
# =====

.PHONY: clean
clean:
	dh_testdir
	dh_clean
	rm -rf build
	rm -rf tests/__pycache__/ tests/*.pyc

# build
# =====

.PHONY: build build-indep build-arch
build build-arch: build/build-stamp
   
build/build-stamp: build/cython-stamp
	dh_testdir
	rm -rf lib/
	$(call loop, $(python2) $(python3), $(parallel)) setup.py build
	export CFLAGS="$$CFLAGS_noopt" && $(call loop, $(python2d) $(python3d), $(parallel)) setup.py build
ifeq "$(filter nocheck,$(DEB_BUILD_OPTIONS))" ""
	$(call loop, $(python_all),) debian/run-tests.py
endif

build/cython-stamp:
	dh_testdir
	mkdir -p build/
	rm -f src/*.cpp
	cython --cplus src/*.pyx
	touch $(@)

# binary
# ======

.PHONY: binary binary-indep binary-arch
binary binary-arch: build/build-stamp
	dh_testdir
	dh_testroot
	dh_prep
	$(call loop, $(python2),) setup.py install --root=debian/python-dawg/
	$(call loop, $(python2d),) setup.py install --root=debian/python-dawg-dbg/
	$(call loop, $(python3),) setup.py install --root=debian/python3-dawg/
	$(call loop, $(python3d),) setup.py install --root=debian/python3-dawg-dbg/
	dh_installdocs README.rst
	dh_installchangelogs
	dh_compress
	dh_fixperms
	dh_strip -p python-dawg --dbg-package python-dawg-dbg
	dh_strip -p python3-dawg --dbg-package python3-dawg-dbg
	dh_shlibdeps
	dh_python2 -p python-dawg -p python-dawg-dbg
	dh_python3 -p python3-dawg -p python3-dawg-dbg
	dh_installdeb
	dh_gencontrol -- -Vdawgdic:Version=$(dawgdic_version)
	dh_md5sums
	dh_builddeb -- -Zxz
	
# vim:ts=4 sw=4 noet
