#!/usr/bin/make -f
# -*- mode: makefile; coding: utf-8 -*-

export DEB_BUILD_MAINT_OPTIONS = hardening=+all

# Pass hardening flags into distutils, explicitly
export CFLAGS   = $(shell dpkg-buildflags --get CFLAGS)
export CPPFLAGS = $(shell dpkg-buildflags --get CPPFLAGS)
export CXXFLAGS = $(shell dpkg-buildflags --get CXXFLAGS)

PACKAGE3_NAME = python3-pandas
PACKAGE3_ROOT_DIR = debian/${PACKAGE3_NAME}

PY3VERS = $(shell py3versions -vr)
PY3VER = $(shell py3versions -vd)
SOURCE_DATE:=$(shell date -u -d "@$(SOURCE_DATE_EPOCH)" "+%a, %d %b %Y" || echo "xxx, xx xxx xxxx")
SOURCE_TIME:=$(shell date -u -d "@$(SOURCE_DATE_EPOCH)" "+%T" || echo "xx:xx:xx")

UVER := $(shell LC_ALL=C dpkg-parsechangelog | awk '/^Version:/{print $$2;}' | sed -e 's,-[^-]*$$,,g' | sed -e 's,+dfsg,,g')
# Python doesn't use ~ for rc
UVER_PY := $(shell echo $(UVER) | sed -e 's,[~],,g')
UVER_PYSHORT := $(shell echo $(UVER_PY) | sed -e 's,+git.*,,g')

MIN_CYTHONVER = 0.23

# Filter out tests with "marker expressions" and "keyword expressions". Ref: pytest(1)
ifeq ($(DEB_HOST_ARCH),$(filter $(DEB_HOST_ARCH), amd64 i386 kfreebsd-amd64 kfreebsd-i386 x32))
	PYTEST_MARKER_ARCH :=
	PYTEST_KEYWORD_ARCH :=
else
	PYTEST_MARKER_ARCH := and not intel and not slow
	PYTEST_KEYWORD_ARCH :=
endif

PYTEST_MARKER := not network $(PYTEST_MARKER_ARCH)

ADDPATCHES :=
# testing for version became fragile: https://github.com/pytest-dev/pytest/issues/3692
# PYTESTVER := $(shell python -c 'import pytest; print(pytest.__version__)')
# and there is way too many uses of pytest.param now, so we can't just easily patch for it... THINK!
# ADDPATCHES += $(shell dpkg --compare-versions $(PYTESTVER) ge 3.1.0 || echo "0001-TST-pytest-deprecation-warnings-GH17197-17253-reversed.patch" )

# MPLVER := $(shell dpkg -l python-matplotlib | awk '/^ii/{print $$3;}' || echo 0)
# $(shell dpkg --compare-versions $(MPLVER) lt 1.0 && echo '|test_hist|test_plot|test_boxplot|test_corr_rank' || echo '')

# try to prevent unsunctioned downloads
export  http_proxy=http://127.0.0.1:9/
export  https_proxy=http://127.0.0.1:9/

export SHELL=/bin/bash

# Mega rule
%:
	: # Explicit build system to avoid use of all-in-1 Makefile
	dh $@ --buildsystem=pybuild --with python3

clean_generated:
	find pandas/ -regex '.*\.c\(\|pp\)' | xargs grep -l -e 'Generated by Cython'  | xargs -r rm -f

_cythonize%:
	debian/rules clean_generated # force removal of previous copies
	python$(*:2=) setup.py cython
	D=debian/cythonized-files$(*:2=) && \
		git rm -rf $$D; \
		find pandas/ -regex '.*\.c\(\|pp\)' | while read f; do \
			grep -q 'Generated by Cython' "$$f" || continue; \
			mkdir -p "$$D/$$(dirname $$f)"; \
			cp "$$f" "$$D/$$(dirname $$f)"; \
			git add -f "$$D/$$f"; \
		done; \
		echo "$(UVER)" >| $$D/VERSION; git add $$D/VERSION

_uncythonize%:
	echo "$*" | grep -q '^3' && PY=3 || PY= ; \
	CYTHONVER=$$(dpkg -l cython$$PY 2>/dev/null | awk '/^ii/{print $$3;}' || echo 0); \
	dpkg --compare-versions "$$CYTHONVER" lt "$(MIN_CYTHONVER)" && { \
		echo "I: Using pre-Cython-ed files for Python $*"; \
		cd debian/cythonized-files$$PY/ ; \
		find . -regex '.*\.c\(\|pp\)' | while read f; do cp $$f ../../$$f; done; } || :

cythonize: _cythonize3

override_dh_clean: clean_generated
	: # Make sure that cythonized sources are up-to-date
	[ ! -e debian/cythonized-files3/VERSION ] || [ "$(UVER)" = "`cat debian/cythonized-files3/VERSION`" ]
	rm -rf build doc/_build *-stamp # pandas.egg-info pandas/datasets/__config__.py
	dh_clean

version_py:
	[ -e pandas/__version.py ] || \
      echo -e "version = '$(UVER_PY)'\nshort_version = '$(UVER_PYSHORT)'" > pandas/__version.py

override_dh_auto_build: version_py debian/patch-stamp
	# Override default build operation which --force's re-cythonization
	# on elderly ubuntus
	# Just build the version.py file
	:

debian/patch-stamp:
	if echo "${ADDPATCHES}" | sed -e 's,\s,,g' | grep  '.' ; then \
       echo ${ADDPATCHES} >> debian/patches/series; \
	   quilt push -a; \
    fi
	touch $@


override_dh_auto_install: ${PY3VERS:%=python-install%} ${PY3VERS:%=python-test%}
# Per Python version logic -- install, test, remomove .so (installed into -lib)
python-install%: _uncythonize%
	python$* setup.py install --install-layout=deb --root=$(CURDIR)/debian/tmp

python-test%: python-install%
ifeq (,$(filter nocheck,$(DEB_BUILD_OPTIONS)))
	echo "backend : Agg" >| $(CURDIR)/build/matplotlibrc
	: # Run unittests here against installed pandas, in sections to avoid out-of-memory crash (#943732); exit code 5 means no tests in this file
	echo "$*" | grep -q '^3' && PY=3 || PY=$*; \
	 export PYTHONPATH=`/bin/ls -d $$PWD/debian/tmp/usr/lib/python$$PY/*/`; \
	 export MPLCONFIGDIR=$(CURDIR)/build HOME=$(CURDIR)/build; \
	 python$* pandas/util/_print_versions.py; \
	 cd build/; TEST_SUCCESS=true; for TEST_SUBSET in $${PYTHONPATH}/pandas/tests/* ; do \
	 LOCALE_OVERRIDE=C xvfb-run -a -s "-screen 0 1280x1024x24 -noreset" \
	 python$* -m pytest -s -v -m "$(PYTEST_MARKER)" --confcutdir=$${PYTHONPATH}/pandas --deb-data-root-dir=$(CURDIR)/pandas/tests --strict-data-files $${TEST_SUBSET} || test $$? == 5 || TEST_SUCCESS=false \
	 ; done ; $${TEST_SUCCESS}
else
	: # Skip unittests due to nocheck
endif

override_dh_installdocs:
	: # Build Documentation using installed pandas
ifeq (,$(filter nodoc,$(DEB_BUILD_OPTIONS)))
ifneq (,$(findstring -a,$(DH_INTERNAL_OPTIONS)))
	: # not building documentation in -a
else
	cd doc && PYTHONPATH=$(CURDIR)/$(PACKAGE3_ROOT_DIR)-lib/usr/lib/python3/dist-packages:$(CURDIR)/$(PACKAGE3_ROOT_DIR)/usr/lib/python3/dist-packages MPLCONFIGDIR=$(CURDIR)/build HOME=$(CURDIR)/build LC_ALL=C python3 make.py html
	# strip build paths and statsmodels timestamps for reproducibility, and online Javascript for privacy
	for html in `find doc/build/html -name _modules -prune -o -name "*.html" -o -name "*.ipynb"` ; do \
	    sed -i -e 's#$(CURDIR)/.pybuild/[^/]*/build/pandas/#/usr/lib/python3/dist-packages/pandas/#g' \
	    -e 's#$(CURDIR)/debian/python3-pandas/usr/lib/python3/dist-packages/pandas/#/usr/lib/python3/dist-packages/pandas/#g' \
	    -e 's#<script crossorigin="anonymous" integrity="sha256-Ae2Vz/4ePdIu6ZyI/5ZGsYnb+m0JlOmKPjt6XZ9JJkA=" type="text/javascript" src="https://cdnjs\.cloudflare\.com/ajax/libs/require\.js/2\.3\.4/require\.min\.js">#<script crossorigin="anonymous" type="text/javascript" src="file:///usr/share/javascript/requirejs/require.min.js">#g' \
	    -e 's#\(Date:.*\)[A-Z][a-z]\+, \+[0-9]\+,\? \+[A-Z][a-z]\+,\? \+[0-9]\+#\1$(SOURCE_DATE)#g' \
	    -e 's#\(Time:.*\)[0-9][0-9]:[0-9][0-9]:[0-9][0-9]#\1$(SOURCE_TIME)#g' $${html} ; \
	done
endif
endif
	: # Use jquery from Debian package, so prune shipped one
	#TODO -rm doc/_build/html/_static/jquery.js
	dh_installdocs -A *.md
	cp -av debian/contributors_list.txt debian/python-pandas-doc/usr/share/doc/python-pandas-doc || true
	# deduplicate files - the ||true is because we only build-depend on jdupes if we're building documentation
	jdupes -r -l debian/python-pandas-doc/usr/share/doc || true

override_dh_install:
	dh_install
	find debian -name __pycache__ | xargs rm -rf

## remove .so libraries from main package, and call dh_numpy*
## while removing 2 if not present
_dh_python%:
	[ -e /usr/bin/dh_numpy$(*:2=) ] && dh_numpy$(*:2=) -p$(PACKAGE$*_NAME)-lib || :
	dh_python$*
	-find debian/python*-pandas -name "*.so" -delete

## "Instantiate" both rules so dh sees them
override_dh_python3: _dh_python3

## immediately useable documentation and exemplar scripts/data
override_dh_compress:
	dh_compress -X.py -X.html -X.pdf -X.css -X.jpg -X.txt -X.js -X.json -X.rtc -Xobjects.inv

override_dh_auto_test:
	# do nothing here, we run tests in python-test% instead
	true