#!/usr/bin/make -f
# See debhelper(7) (uncomment to enable)
# output every command that modifies files on the build system.
#export DH_VERBOSE = 1

export DEB_HOST_MULTIARCH ?= $(shell dpkg-architecture -qDEB_HOST_MULTIARCH)

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')

VERSION := $(DEB_STRIPPED_UPSTREAM_VERSION)
MAJOR_VERSION := $(shell echo $(DEB_STRIPPED_UPSTREAM_VERSION) | sed "s/^\([^.]*\)\..*$$/\1/")
SOVERSION := $(MAJOR_VERSION)

PY3VERS := $(shell py3versions -v --requested debian/control | tac -s' ')
PY3VER_DEFAULT := $(shell py3versions -dv)

%:
	dh $@ --with python3,sphinxdoc --buildsystem=cmake


override_dh_auto_clean:
	dh_auto_clean
	rm -rf cpp/doc/html cpp/doc/latex
	rm -rf .pybuild
	rm -rf python/fenics_basix.egg-info
	rm -rf python/doc/build
	rm -rf test/.pytest_cache  test/__pycache__  python/testing_build

override_dh_auto_build-indep: export http_proxy=127.0.0.1:9
override_dh_auto_build-indep: export https_proxy=127.0.0.1:9
override_dh_auto_build-indep:
	dh_auto_build -i
	cd cpp/doc; doxygen

override_dh_auto_install:
	dh_auto_install
	for v in $(PY3VERS); do \
	  echo cd python; \
	  LD_LIBRARY_PATH=$(CURDIR)/debian/tmp/usr/lib/$(DEB_HOST_MULTIARCH) CMAKE_PREFIX_PATH=$(CURDIR)/debian/tmp/usr/lib/$(DEB_HOST_MULTIARCH)/cmake  pybuild --dir=$(CURDIR)/python --install --system=distutils --name=basix; \
	  cd ..; \
	done
	LD_LIBRARY_PATH=$(CURDIR)/debian/tmp/usr/lib/$(DEB_HOST_MULTIARCH) PYTHONPATH=$(CURDIR)/debian/python3-basix/usr/lib/python$(PY3VER_DEFAULT)/dist-packages:${PYTHONPATH} $(MAKE) -C python/doc html
	sed 's|href="https://fenicsproject.org/docs/basix/main/cpp/"|href="file:/usr/share/doc/basix-doc/cpp/index.html"|' -i python/doc/build/html/index.html

override_dh_installdocs-indep:
	dh_installdocs -i
	grep "https://cdnjs.cloudflare.com/ajax/libs/mathjax/.*/MathJax.js" debian/basix-doc/usr/share/doc/basix-doc/* -r --files-with-matches | xargs sed "s|src=\"https://cdnjs.cloudflare.com/ajax/libs/mathjax/.*/MathJax.js|src=\"file://usr/share/javascript/mathjax/MathJax.js|g" -i

ifeq (,$(filter nocheck,$(DEB_BUILD_OPTIONS)))
override_dh_python3:
	dh_python3
	cd test; LD_LIBRARY_PATH=$(CURDIR)/debian/tmp/usr/lib/$(DEB_HOST_MULTIARCH) PYTHONPATH=$(shell pybuild --name basix -p $(PY3VER_DEFAULT) --print {build_dir}) pytest-3
endif
