#!/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

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 PYBUILD_NAME = sage

%:
	dh $@ --with=python3,sphinxdoc --buildsystem=pybuild --sourcedir=sage/pkgs/sagemath-standard

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

binary build clean install: debian/control

debian/control: debian/control.in
	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:
	cd sage/pkgs/sage-setup && python3 setup.py build
	cd sage/pkgs/sage-setup && python3 setup.py install --root=$(CURDIR)/debian/tmp0 --install-layout=deb
	export PYTHONPATH=$(CURDIR)/debian/tmp0/usr/lib/python3/dist-packages && 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/tmp/usr/bin/sage:
	cp -f debian/sage_conf.py sage/pkgs/sagemath-standard/
# Generate setup.cfg etc in sage/src from .m4 files:
	cd sage/build/pkgs/sagelib && SAGE_ROOT=$(CURDIR)/sage PATH=$(PATH):$(CURDIR)/sage/build/bin ./bootstrap
# Remove sage-conf from setup.cfg, it can lead to a dependency on sagemath-common
	sed -i '/sage-conf/d' sage/src/setup.cfg
	export PYTHONPATH=$(CURDIR)/debian/tmp0/usr/lib/python3/dist-packages && dh_auto_build
	export PYTHONPATH=$(CURDIR)/debian/tmp0/usr/lib/python3/dist-packages && dh_auto_install
	mkdir -p debian/tmp
	mv debian/python3-sage/usr debian/tmp/
	rm -rf debian/python3-sage
	mkdir -p debian/tmp/usr/lib/python3.11/dist-packages/
	cp -f debian/sage_conf.py debian/tmp/usr/lib/python3.11/dist-packages/

override_dh_auto_build-arch: debian/tmp/usr/bin/sage

override_dh_auto_build-indep: debian/tmp/usr/bin/sage
ifeq (,$(filter nodoc,$(DEB_BUILD_PROFILES)))
	cd sage && SAGE_ROOT=$(CURDIR)/sage PATH=$(PATH):$(CURDIR)/sage/build/bin src/doc/bootstrap
	mv sage/src/sage sage/src/sage.bak # Use the installed sage, not the one from the source tree
	cd sage/src && \
	export PYTHONPATH=$(CURDIR)/debian/tmp/usr/lib/python3.11/dist-packages \
	       SAGE_SRC=$(CURDIR)/sage/src \
	       SAGE_DOC_SRC=$(CURDIR)/sage/src/doc \
	       SAGE_DOC=$(CURDIR)/sage/src/doc \
	       MATHJAX_DIR=/usr/share/javascript/mathjax \
	       LANG=C && \
	python3 -m sage_docbuild --no-pdf-links --mathjax all html
	mv sage/src/sage.bak sage/src/sage
	mkdir -p debian/tmp/usr/share/doc/sagemath
	mv sage/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 sage/src/sage/ext_data/notebook-ipython/logo-64x64.png debian/tmp/usr/share/icons/hicolor/64x64/apps/sagemath.png
	cp -f sage/src/sage/ext_data/notebook-ipython/logo.svg debian/tmp/usr/share/icons/hicolor/scalable/apps/sagemath.svg
# Fix links to icons.
	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

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

override_dh_install-indep:
	dh_install
ifeq (,$(filter nodoc,$(DEB_BUILD_PROFILES)))
# Basic version of deduplicating the docs, for a much smaller install size.
# Upstream bug report is at https://trac.sagemath.org/ticket/22088
# Hard links do work in Debian packages, but only within packages.
	rdfind -outputname /dev/null -makehardlinks true debian/sagemath-doc;
endif

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
endif

override_dh_clean:
	rm -rf .sage .texlive2021 debian/python3-sage-dbg
	rm -f sage/pkgs/sagemath-standard/sage_conf.py
	dh_clean

override_dh_auto_clean:

#override_dh_strip:
#	dh_strip -ppython3-sage --dbg-package=python3-sage-dbg

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.11/dist-packages \
	       SAGE_DOC=$(CURDIR)/sage/src/doc \
	       SAGE_LOCAL=/usr && cd sage && \
	sage -t -p $(SAGE_NUM_THREADS) --logfile=$(CURDIR)/sage/logs/ptestlong-$(1).log $(2)

rerun_tests = \
	export PATH=$(PATH):$(CURDIR)/debian/tmp/usr/bin \
	       PYTHONPATH=$(CURDIR)/debian/tmp/usr/lib/python3.11/dist-packages \
	       SAGE_DOC=$(CURDIR)/sage/src/doc \
	       SAGE_LOCAL=/usr && cd sage && \
	sage -t -p 1 -f --logfile=$(CURDIR)/sage/logs/ptestlong-$(1).log $(2)

run_tests_with_retry = \
	$(run_tests); cd "$(CURDIR)" && \
	if $(TESTS_MK) LOGFILE=sage/logs/ptestlong-$(1).log MAX_TEST_FAILURES=$(3) had-few-failures; then :; else \
	  $(TESTS_MK) LOGFILE=sage/logs/ptestlong-$(1).log MAX_TEST_FAILURES=$(3) had-not-too-many-failures && \
	  mv sage/logs/ptestlong-$(1).log sage/logs/ptestlong-$(1).log.1 && \
	  { $(rerun_tests); cd "$(CURDIR)" && \
	  $(TESTS_MK) LOGFILE=sage/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 sage/logs
	$(call run_tests_with_retry,arch,$(SAGE_TEST_FLAGS_ARCH) src/sage,200)
endif

override_dh_auto_test-indep:
ifeq (,$(filter nodoc,$(DEB_BUILD_PROFILES)))
ifeq (,$(filter nocheck,$(DEB_BUILD_OPTIONS)))
	mkdir -p sage/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 sage/logs/dochtml.log | grep -v "citation not found: .*Error\|Citation \[.*Error\] is not referenced")
endif
endif

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

distclean:
	rm -f debian/control
	cd sage; git clean -fdx && git reset --hard HEAD && git submodule update --force
	# don't git reset --hard on purpose, so it's easier to test
	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

get-orig-source: .git/modules/sage/HEAD
	cd sage && git archive --prefix=sagemath_$(DEB_VERSION_UPSTREAM)/sage/ \
	  --format=tar HEAD | xz -zf > ../../sagemath_$(DEB_VERSION_UPSTREAM).orig.tar.xz
