#!/usr/bin/make -f

#
# CONTENTS:
#
# 1. DEFINITIONS
# 2. GENERATE FILES
#    Targets to auto-generate files
# 3. PACKAGE BUILD
#    Mostly standard targets that are used during package build
# 4. TEST SUITE
# 5. MAINTAINER TARGETS
#    Convenience targets to be used by maintainers
#    Some are explained at https://wiki.debian.org/DebianScience/Sage
#

###############################################################################
# 1. DEFINITIONS
###############################################################################

include /usr/share/dpkg/pkg-info.mk
include /usr/share/dpkg/architecture.mk

PY3VER = $(shell py3versions -dv)

ifneq (,$(filter parallel=%,$(DEB_BUILD_OPTIONS)))
export SAGE_NUM_THREADS = $(patsubst parallel=%,%,$(filter parallel=%,$(DEB_BUILD_OPTIONS)))
endif

# Some buildds are a bit slow, see https://buildd.debian.org/status/logs.php?pkg=gcc-7 for a fuller list
ifneq (,$(filter $(DEB_BUILD_ARCH),armel armhf mips mipsel mips64el))
export SAGE_TIMEOUT_LONG = 7200
else
export SAGE_TIMEOUT_LONG = 3600
endif

export HOME = $(CURDIR)
export DEB_BUILD_MAINT_OPTIONS = hardening=+all
export PYBUILD_NAME = sage
export PYBUILD_SYSTEM = pyproject
export PYBUILD_DISABLE = *dbg
unexport DISPLAY
export PYBUILD_DESTDIR = debian/tmp

%:
	dh $@ --with=python3,sphinxdoc --without=autoreconf --buildsystem=pybuild

###############################################################################
# 2. GENERATE FILES
###############################################################################

binary build clean install: debian/control

debian/control: debian/control.in debian/control.runtime-depends debian/control.runtime-recommends debian/control.jupyter-depends
	cat $< > "$@"
	sed -i -e '/RUNTIME_DEPENDS/ {' -e 'r debian/control.runtime-depends' -e 'd' -e '}' "$@"
	sed -i -e '/RUNTIME_RECOMMENDS/ {' -e 'r debian/control.runtime-recommends' -e 'd' -e '}' "$@"
	sed -i -e '/JUPYTER_DEPENDS/ {' -e 'r debian/control.jupyter-depends' -e 'd' -e '}' "$@"

###############################################################################
# 3. PACKAGE BUILD
###############################################################################

override_dh_auto_configure:
	dh_auto_configure

# We install directly after building in order to use the python package for
# docbuild and testing. This is required both for arch and indep builds.
debian/stamp-build-install:
	dh_auto_build
	dh_auto_install --destdir=debian/tmp
	mkdir -p debian/tmp/usr/lib/python3/dist-packages/
	cp -f debian/sage_conf.py debian/tmp/usr/lib/python3/dist-packages/
	if [ -d debian/tmp/usr/lib/python$(PY3VER)/dist-packages ]; then \
		cp -f debian/sage_conf.py debian/tmp/usr/lib/python$(PY3VER)/dist-packages/; \
	fi
	touch $@

override_dh_auto_build-arch: debian/stamp-build-install

override_dh_auto_build-indep: debian/stamp-build-install
ifeq (,$(filter nodoc,$(DEB_BUILD_PROFILES)))
	PYTHONPATH=$(CURDIR)/debian/tmp/usr/lib/python3/dist-packages:$(CURDIR)/debian/tmp/usr/lib/python$(PY3VER)/dist-packages \
	SAGE_SRC=$(CURDIR)/src \
	SAGE_DOC_SRC=$(CURDIR)/src/doc \
	MATHJAX_DIR=/usr/share/javascript/mathjax \
	LANG=C.UTF-8 \
	ninja -C .pybuild/cpython3_$(PY3VER)_sage/meson-build doc-html
	mkdir -p debian/tmp/usr/share/doc/sagemath
	rm -rf debian/tmp/usr/share/doc/sagemath/html
	mv .pybuild/cpython3_$(PY3VER)_sage/meson-build/src/doc/html debian/tmp/usr/share/doc/sagemath/
	cd debian/tmp/usr/share/doc/sagemath/html && \
	for statdir in */*/_static; do ln -s /usr/share/javascript/mathjax "$$statdir"; done && \
	for statdir in */_static; do ln -s /usr/share/javascript/mathjax "$$statdir"; done
endif

override_dh_auto_install:
	# Delete .bat files
	rm -f debian/tmp/usr/bin/*.bat
	# Install desktop file
	mkdir -p debian/tmp/usr/share/applications
	cp -f debian/sagemath.desktop debian/tmp/usr/share/applications/sagemath.desktop
	# Install (renamed) icons.
	mkdir -p debian/tmp/usr/share/icons/hicolor/64x64/apps
	mkdir -p debian/tmp/usr/share/icons/hicolor/scalable/apps
	cp -f src/sage/ext_data/notebook-ipython/logo-64x64.png debian/tmp/usr/share/icons/hicolor/64x64/apps/sagemath.png
	cp -f src/sage/ext_data/notebook-ipython/logo.svg debian/tmp/usr/share/icons/hicolor/scalable/apps/sagemath.svg
	# Fix links to icons.
	mkdir -p debian/tmp/usr/share/jupyter/kernels/sagemath
	cd debian/tmp/usr/share/jupyter/kernels/sagemath && rm -f logo-64x64.png && \
	   ln -s ../../../icons/hicolor/64x64/apps/sagemath.png logo-64x64.png
	cd debian/tmp/usr/share/jupyter/kernels/sagemath && rm -f logo.svg && \
	   ln -s ../../../icons/hicolor/scalable/apps/sagemath.svg logo.svg
	# Remove non-standard RPATH/RUNPATH from python extension modules
	find debian/tmp -name "*.so" -exec chrpath -d {} + 2>/dev/null || true
	# Remove shebang from non-executable ext_data test script
	find debian/tmp -name "testall" -exec sed -i '1{/^#!/d}' {} +

override_dh_prep:
# Prevent dh_prep from deleting debian/tmp.
	dh_prep -Xdebian/tmp

override_dh_install-indep:
	dh_install

override_dh_installman-indep:
	dh_installman -psagemath debian/sage.1

override_dh_missing:
	dh_missing --list-missing

override_dh_python3-arch:
	dh_python3
	dh_numpy3 --package python3-sage # stop lintian complaining at us

override_dh_compress:
# We probably don't need to install the pickle/doctree files but let's exempt
# them from compression anyway for now, so the build goes quicker.
	dh_compress -X.pdf -X.pickle -X.doctree

override_dh_sphinxdoc:
ifeq (,$(filter nodoc,$(DEB_BUILD_PROFILES)))
# TODO: fix MathJax.js, Sage needs special treatment
# `man dh_sphinxdoc` says symlinking translations.js is not yet supported
# likewise, it seems not to recognise searchtools.js yet
	dh_sphinxdoc -XMathJax.js -Xtranslations.js -Xsearchtools.js
	# Deduplicate remaining documentation files using symlinks to reduce package size.
	rdfind -outputname /dev/null -makesymlinks true debian/sagemath-doc;
	# Convert any absolute build-tree symlinks from rdfind into relative symlinks
	python3 -c 'import os; pkg = os.path.abspath("debian/sagemath-doc"); [(os.unlink(p), os.symlink(os.path.relpath(t, r), p)) for r, _, fs in os.walk(pkg) for f in fs for p in [os.path.join(r, f)] if os.path.islink(p) for t in [os.readlink(p)] if t.startswith(pkg)]'
endif

override_dh_clean:
	rm -rf .sage .texlive2021 .pybuild debian/python3-sage-dbg debian/stamp-build-install logs
	rm -f sage_conf.py
	dh_clean

override_dh_auto_clean:


override_dh_strip_nondeterminism:
	dh_strip_nondeterminism -X.png # On png files it sometimes fails claiming it's not a png file.

###############################################################################
# 4. TEST SUITE
###############################################################################

ifeq (,$(filter pkg.sagemath.nolongcheck,$(DEB_BUILD_PROFILES)))
SAGE_TEST_FLAGS_ARCH = --optional=sage,python3,memlimit --long
SAGE_TEST_FLAGS_INDEP = --optional=sage,python3,memlimit,dochtml --long
else
SAGE_TEST_FLAGS_ARCH = --optional=sage,python3,memlimit
SAGE_TEST_FLAGS_INDEP = --optional=sage,python3,memlimit,dochtml
endif

TESTS_MK = $(MAKE) -s --no-print-directory -f debian/tests.mk LOGFILE=$(LOGFILE)

run_tests = \
	export PATH=$(PATH):$(CURDIR)/debian/tmp/usr/bin \
	       PYTHONPATH=$(CURDIR)/debian/tmp/usr/lib/python3/dist-packages:$(CURDIR)/debian/tmp/usr/lib/python$(PY3VER)/dist-packages \
	       SAGE_DOC=$(CURDIR)/src/doc \
	       SAGE_LOCAL=/usr \
	       OPENBLAS_NUM_THREADS=1 \
	       OMP_NUM_THREADS=1 && \
	unset DISPLAY && \
	python3 -m sage.doctest -p $(SAGE_NUM_THREADS) --logfile=$(CURDIR)/logs/ptestlong-$(1).log $(2)

rerun_tests = \
	export PATH=$(PATH):$(CURDIR)/debian/tmp/usr/bin \
	       PYTHONPATH=$(CURDIR)/debian/tmp/usr/lib/python3/dist-packages:$(CURDIR)/debian/tmp/usr/lib/python$(PY3VER)/dist-packages \
	       SAGE_DOC=$(CURDIR)/src/doc \
	       SAGE_LOCAL=/usr \
	       OPENBLAS_NUM_THREADS=1 \
	       OMP_NUM_THREADS=1 && \
	unset DISPLAY && \
	python3 -m sage.doctest -p 1 -f --logfile=$(CURDIR)/logs/ptestlong-$(1).log $(2)

run_tests_with_retry = \
	$(run_tests); cd "$(CURDIR)" && \
	if $(TESTS_MK) LOGFILE=logs/ptestlong-$(1).log MAX_TEST_FAILURES=$(3) had-few-failures; then :; else \
	  $(TESTS_MK) LOGFILE=logs/ptestlong-$(1).log MAX_TEST_FAILURES=$(3) had-not-too-many-failures && \
	  mv logs/ptestlong-$(1).log logs/ptestlong-$(1).log.1 && \
	  { $(rerun_tests); cd "$(CURDIR)" && \
	  $(TESTS_MK) LOGFILE=logs/ptestlong-$(1).log MAX_TEST_FAILURES=$(3) had-few-failures; }; \
	fi

override_dh_auto_test-arch:
ifeq (,$(filter nocheck,$(DEB_BUILD_OPTIONS)))
	mkdir -p logs
	$(call run_tests_with_retry,arch,$(SAGE_TEST_FLAGS_ARCH) src/sage,2000)
endif

override_dh_auto_test-indep:
ifeq (,$(filter nodoc,$(DEB_BUILD_PROFILES)))
ifeq (,$(filter nocheck,$(DEB_BUILD_OPTIONS)))
	mkdir -p logs
	$(call run_tests_with_retry,indep,$(SAGE_TEST_FLAGS_INDEP) src/doc src/sage/misc/sagedoc.py,50)
	# Sometimes, parts of the docbuild fail with MemoryError or OSError but
	# Sage doesn't detect this. Here we detect it and fail the build if so.
	# Also filter out some false positives that are not hard errors.
	! (grep Error logs/dochtml.log 2>/dev/null | grep -v "citation not found: .*Error\|Citation \[.*Error\] is not referenced")
endif
endif

###############################################################################
# 5. MAINTAINER TARGETS
###############################################################################

distclean:
	rm -f debian/control
	git clean -fdx
	debian/rules debian/control

build-dep-maint:
	sudo apt-get install --no-install-recommends equivs devscripts git iso-codes python3 quilt

build-dep: debian/control
	if which aptitude >/dev/null; then sudo -E mk-build-deps -ir -t 'aptitude -R'; \
	else sudo -E mk-build-deps -ir; fi
