#!/usr/bin/make -f

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

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

# For testing, we need .egg-info so the entry points are available.
export PYBUILD_BEFORE_TEST=python{version} setup.py develop --install-dir {build_dir}
# Delete .egg-info and other files that were generated along with .egg-info
export PYBUILD_BEFORE_INSTALL=rm -rvf {build_dir}/q2-types.egg-* {build_dir}/site.py \
	{build_dir}/.coverage* {build_dir}/easy-install.pth

%:
	dh $@ --buildsystem=pybuild

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

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; \
	    pkg=q2_types; \
	    ignores=(); \
	    while : ; do \
	        new=0; \
	        errs=$$($${py} -m pytest --collect-only -q "$${ignores[@]}" 2>&1 || true); \
	        for f in $$(sed -n 's/^ERROR \(q2_types\/.*\.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[@]}"; \
	    cd $(CURDIR); \
	done
endif

override_dh_install:
	dh_install -pq2-types --exclude=/reference_db/tests/data
	dh_install -pq2-types-examples
	find debian -name ".coverage*" -delete

execute_after_dh_auto_clean:
	rm -fr q2_types.egg-info/PKG-INFO q2_types.egg-info/SOURCES.txt q2_types.egg-info/dependency_links.txt q2_types.egg-info/entry_points.txt q2_types.egg-info/not-zip-safe q2_types.egg-info/top_level.txt

execute_after_dh_fixperms:
	find debian  \( -name "*.fa" -o -name "*.txt" \) -exec chmod -x \{\} \;
