#!/usr/bin/make -f

# DH_VERBOSE := 1
export LC_ALL=C.UTF-8
SHELL=/bin/bash

export PYBUILD_BEFORE_TEST=mkdir -v {build_dir}/q2_taxa/assets/barplot/dist
export PYBUILD_BEFORE_INSTALL=rm -rvf {build_dir}/.coverage*

include /usr/share/dpkg/default.mk
VERSION_UPSTREAM=$(shell echo $(DEB_VERSION_UPSTREAM) | sed -e 's/\(20[0-9][0-9]\.[0-9]\+\)\..*/\1/')

debian/control: debian/control.in
	echo "# This file is autogenerated from control.in to update versioned dependencies" > $@
	sed -e"s/@DEB_VERSION_UPSTREAM@/$(VERSION_UPSTREAM)/g" $< >> $@

pkg:=q2_taxa

%:
	dh $@ --buildsystem=pybuild

override_dh_auto_build:
	dh_auto_build
	set -e; \
	for d in .pybuild/cpython3_*/build; do \
	    cd "$$d/q2_taxa/assets/barplot"; \
	    webpack --bail; \
	    cd $(CURDIR); \
	done

override_dh_auto_clean:
	dh_auto_clean
	rm -f q2_taxa.egg-info/PKG-INFO q2_taxa.egg-info/SOURCES.txt q2_taxa.egg-info/dependency_links.txt q2_taxa.egg-info/entry_points.txt q2_taxa.egg-info/not-zip-safe q2_taxa.egg-info/top_level.txt

override_dh_auto_test:
ifeq (,$(filter nocheck,$(DEB_BUILD_OPTIONS)))
	set -e; \
	for d in .pybuild/cpython3_*/build; do \
	    py=python$$(basename $$(dirname $$d) | sed 's/^cpython3_//'); \
	    cd $$d; \
            ignores=(); \
	    while : ; do \
	         new=0; \
	         errs=$$($${py} -m pytest --collect-only -q "$${ignores[@]}" 2>&1 || true); \
	         for f in $$(sed -n 's/^ERROR \($(pkg)\/.*\.py\).*/\1/p' \
	                    <<<"$${errs}" | sort -u); do \
	             mod=$${f%.py}; \
	             mod=$${mod//\//.}; \
	             out=$$($${py} -c "import $${mod}" 2>&1 || true); \
	             miss=$$(sed -n "s/.*No module named '\([^']*\)'.*/\1/p" \
	                    <<<"$${out}" | tail -1); \
	             if [ -n "$${miss}" ] && [[ "$${miss}" != "$(pkg)"* ]] ; then \
                         echo "Ignoring $${f}: $${miss} not packaged in Debian"; \
	                 ignores+=(--ignore="$${f}"); \
	                 new=1; \
	             fi; \
	         done; \
	         [ "$${new}" = 1 ] || break; \
	     done; \
	     $${py} -m pytest -v --cov=$(pkg) "$${ignores[@]}" -k "not test_examples"; \
	     cd $(CURDIR); \
	 done
endif
