#!/usr/bin/make -f

%:
	dh $@

override_dh_auto_configure:

override_dh_auto_build:
	# webpack resolves bare module names from the source tree rather than
	# from /usr/share/nodejs, so link the system modules it must find:
	# the runtime requires (htmlparser2, domhandler, domutils, fflate,
	# pako, fastest-levenshtein), typescript for ts-loader, ts-loader
	# itself as a loader reference, and esbuild, which
	# scripts/build-structured-document-text.js imports directly.
	# The directory also has to stay writable for webpack's filesystem
	# cache.
	mkdir -p node_modules
	for m in htmlparser2 domhandler domutils fflate pako fastest-levenshtein typescript ts-loader esbuild webpack webpack-cli; do \
	  if [ -d /usr/share/nodejs/$$m ]; then ln -sf /usr/share/nodejs/$$m node_modules/$$m; fi; \
	done
	# The pdf.js image decoders are built from source by pdfjs-jbig2 and
	# pdfjs-openjpeg; webpack reaches them through pdf.js' own core sources
	# (src/core/jbig2_ccittFax.js, src/core/jpx.js) and scripts/build-assets
	# copies them into build/wasm/, so they are put in place first.
	cp /usr/share/javascript/pdfjs-jbig2/jbig2.js pdf.js/external/jbig2/jbig2.js
	cp /usr/share/javascript/pdfjs-jbig2/jbig2.wasm pdf.js/external/jbig2/jbig2.wasm
	cp /usr/share/javascript/pdfjs-jbig2/jbig2_nowasm_fallback.js pdf.js/external/jbig2/jbig2_nowasm_fallback.js
	cp /usr/share/javascript/pdfjs-openjpeg/openjpeg.js pdf.js/external/openjpeg/openjpeg.js
	cp /usr/share/javascript/pdfjs-openjpeg/openjpeg.wasm pdf.js/external/openjpeg/openjpeg.wasm
	cp /usr/share/javascript/pdfjs-openjpeg/openjpeg_nowasm_fallback.js pdf.js/external/openjpeg/openjpeg_nowasm_fallback.js
	webpack --mode production
	bash scripts/build-assets
	node scripts/build-metadata.js
	node scripts/build-structured-document-text.js

override_dh_auto_test:

override_dh_auto_install:

override_dh_install:
	dh_install
	# The CMap and standard font data the renderer asks for under cmaps/
	# and standard_fonts/ belongs to zotero-pdfjs-data; link it in rather
	# than shipping a second copy of it.
	dh_link /usr/share/zotero/resource/pdfjs/bcmaps \
	        /usr/share/zotero/resource/document-worker/cmaps
	dh_link /usr/share/zotero/resource/pdfjs/standard_fonts \
	        /usr/share/zotero/resource/document-worker/standard_fonts

override_dh_clean:
	dh_clean
	rm -rf build node_modules
	# The decoders come from the pdfjs-* packages for the build; remove them
	# individually, the LICENSE_* and README.md next to them belong to this
	# source package.
	rm -f pdf.js/external/jbig2/jbig2.js pdf.js/external/jbig2/jbig2.wasm pdf.js/external/jbig2/jbig2_nowasm_fallback.js
	rm -f pdf.js/external/openjpeg/openjpeg.js pdf.js/external/openjpeg/openjpeg.wasm pdf.js/external/openjpeg/openjpeg_nowasm_fallback.js
