#!/usr/bin/make -f

#export DH_VERBOSE=1
export PYBUILD_NAME=ffcx


# tests must be run manually (outside the build dir)
# since some tests leave generated files in the working directory, interfering with package build
# e.g. test_lnodes.py uses CFFI directly (generates .c, .so)
# test_numba.py generates poisson_numba.py
export PYBUILD_DISABLE=test

DEB_SOURCE_PACKAGE := $(strip $(shell egrep '^Source: ' debian/control | cut -f 2 -d ':'))
DEB_VERSION := $(shell dpkg-parsechangelog | egrep '^Version:' | cut -f 2 -d ' ')
DEB_NOEPOCH_VERSION := $(shell echo $(DEB_VERSION) | cut -d: -f2-)
DEB_UPSTREAM_VERSION := $(shell echo $(DEB_NOEPOCH_VERSION) | sed 's/-[^-]*$$//')
DEB_STRIPPED_UPSTREAM_VERSION = $(shell echo $(DEB_UPSTREAM_VERSION) | sed -e 's/\+dfsg.*$$//p')

FENICS_RELEASE_VERSION=$(DEB_STRIPPED_UPSTREAM_VERSION)
FENICS_MAJOR_VERSION=$(shell echo $(FENICS_RELEASE_VERSION) | sed "s/^\([^.]*\)\..*$$/\1/")
FENICS_MINOR_VERSION=$(shell echo $(FENICS_RELEASE_VERSION) | sed "s/^\([^.]*\)\.\([^.]*\)\..*$$/\2/")
FENICS_VERSION=$(FENICS_MAJOR_VERSION).$(FENICS_MINOR_VERSION)
FENICS_NEXT_VERSION=$(FENICS_MAJOR_VERSION).$(shell echo $$(( $(FENICS_MINOR_VERSION) + 1 )) )

USCAN_DESTDIR := $(CURDIR)

PYTHON_BASE_SCRIPT="import sys; base=list(filter( lambda p: p.startswith('/usr/lib/python') and p.endswith('/dist-packages'), sys.path ))[0]; sys.stdout.write(base)"
PYTHON3_MODULE_BASE := $(shell python3 -c $(PYTHON_BASE_SCRIPT))

PY3VER_DEFAULT := $(shell py3versions -dv)
PY3VERS := $(shell py3versions -sv)

ifeq ($(DEB_HOST_ARCH),s390x)
    TEST_SELECTION = "not test_ds_prism[float64]"
endif


%:
	dh $@ --with sphinxdoc --buildsystem=pybuild

override_dh_compress:
	dh_compress -X.py -X.ufl

execute_after_dh_auto_clean:
	rm -rf doc/source/_autogenerated

execute_after_dh_auto_install:
ifeq (,$(filter nodoc,$(DEB_BUILD_OPTIONS)))
	cd doc; PYTHONPATH=$(CURDIR)/debian/python3-ffcx/usr/lib/python$(PY3VER_DEFAULT)/dist-packages:${PYTHONPATH} python3 -m sphinx -W -b html source/ ../.pybuild/doc/html/
	cd doc; PYTHONPATH=$(CURDIR)/debian/python3-ffcx/usr/lib/python$(PY3VER_DEFAULT)/dist-packages:${PYTHONPATH} python3 -m sphinx -W -b man source/ ../.pybuild/doc/man/
endif
ifeq (,$(filter nocheck,$(DEB_BUILD_OPTIONS)))
	set -e; \
	for py in $(PY3VERS); do \
	  testdir=$(CURDIR)/.pybuild/test_py$$py; \
	  cp -r $(CURDIR)/test $$testdir; \
	  cd $$testdir; \
	  PYTHONPATH=$(CURDIR)/debian/python3-ffcx/usr/lib/python$$py/dist-packages:${PYTHONPATH} \
	    PATH=$(CURDIR)/debian/python3-ffcx/usr/bin:$(PATH) \
	    python$$py -mpytest -k "$(TEST_SELECTION)"; \
	done
endif

override_dh_gencontrol:
	dh_gencontrol -- -Vfenics:Upstream-Version=$(FENICS_VERSION) -Vfenics:Next-Upstream-Version=$(FENICS_NEXT_VERSION)~
