#!/usr/bin/make -f

# Uncomment this to turn on verbose mode.
#export DH_VERBOSE=1

export PYBUILD_NAME=jupyterlab
export JUPYTERLAB_DIR=$(CURDIR)/debian/jupyterlab/usr/share/jupyter/lab
PYVERS=$(shell python3 -c 'import sysconfig;print (sysconfig.get_python_version())')
BUILD_EXTENSIONS=galata/extension
export YARNCOMMAND=pkgjs

# Limit memory consumption to 2/3 of available RAM
NODE_MEM=$(shell if test -e /proc/meminfo; then echo $$((`grep MemTotal /proc/meminfo|sed -e 's/[^0-9]//g'` / 1536 )); else echo 2048; fi)
export NODE_OPTIONS=--max_old_space_size=$(NODE_MEM)
export NODE_ENV=production

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

execute_after_dh_auto_configure:
	dh_auto_configure --buildsystem=nodejs

execute_after_dh_auto_build:
	# Replace html-loader preprocessing
	grep -lr '<%= require(.html-loader'|./debian/html-loader.pl
	# Update build links
	ln -s ../../packages/fileeditor-extension node_modules/@jupyterlab/ || true
	# Build duplicate-package-checker-webpack-plugin
	cd duplicate-package-checker-webpack-plugin && sh -ex ../debian/nodejs/duplicate-package-checker-webpack-plugin/build
	# Build @jupyterlab/* libraries
	sh -ex debian/nodejs/build
	cd jupyterlab/staging && \
		webpack --config webpack.prod.minimize.config.js

execute_after_dh_auto_install:
	# Install Node.js libraries
	dh_auto_install --buildsystem=nodejs

execute_after_dh_install:
	mkdir -p $(JUPYTERLAB_DIR)
	for i in $(shell py3versions -s) ; do \
		ln -s ../../../python3/dist-packages/jupyterlab/staging \
			../../../python3/dist-packages/jupyterlab/node-version-check.js \
		 debian/jupyterlab/usr/lib/$$i/dist-packages/jupyterlab/ || true; \
		cp -f jupyterlab/staging/yarn.js \
			debian/jupyterlab/usr/lib/$$i/dist-packages/jupyterlab/staging/; \
	done
	set -e ; TMPDIR=$$(mktemp -d) ; \
		HOME=$$TMPDIR PYTHONPATH=$(CURDIR)/debian/jupyterlab/usr/lib/python$(PYVERS)/dist-packages/ \
		 debian/jupyterlab/usr/bin/jupyter-lab build ; \
		rm -r $$TMPDIR/
	set -e; for i in $(BUILD_EXTENSIONS) ; do \
		echo Building extension $$i ; \
		TMPDIR=$$(mktemp -d) ; \
		HOME=$$TMPDIR \
		PATH=`pwd`/debian/jupyterlab/usr/bin/:$$PATH \
		PYTHONPATH=$(CURDIR)/debian/jupyterlab/usr/lib/python$(PYVERS)/dist-packages/ \
		 debian/jupyterlab/usr/bin/jupyter-labextension build $$i ; \
		rm -r $$TMPDIR/ ; \
	done
	rm -rf `find debian/jupyterlab -name __pycache__ -o -name node_modules`
	find debian/jupyterlab -name build_log.json -delete

override_dh_auto_test:
	@echo "Tests disabled because of missing depends"

override_dh_installdocs:
	dh_installdocs
	dh_nodejs_autodocs auto_dispatch

override_dh_auto_clean:
	# Restore html-loader.pl modified files
	grep -lr '<%= require(.html-loader' debian|debian/restore-html-loader.pl
	dh_auto_clean -O--buildsystem=pybuild || true
	dh_auto_clean -O--buildsystem=nodejs || true
