#!/usr/bin/make -f

# The build profile hardening flags include -fcf-protection, which is an x86
# Control-flow Enforcement Technology feature and cannot be used when targeting
# wasm32. Strip it before invoking emscripten.
CFLAGS  = $(shell dpkg-buildflags --get CFLAGS  | sed 's/-fcf-protection//g')
CXXFLAGS= $(shell dpkg-buildflags --get CXXFLAGS| sed 's/-fcf-protection//g')
export CFLAGS CXXFLAGS

# A fresh emscripten cache has no pre-built sysroot, so warm it up first.
export EM_CACHE = $(CURDIR)/debian/emcache

%:
	dh $@

override_dh_auto_build:
	mkdir -p $(EM_CACHE)
	printf 'int main(){return 0;}\n' > debian/empp-warmup.c
	emcc debian/empp-warmup.c -o debian/empp-warmup.js
	printf 'int main(){return 0;}\n' > debian/empp-warmup.cpp
	em++ debian/empp-warmup.cpp -o debian/empp-warmup.js
	rm -f debian/empp-warmup.*
	tar -xjf src/libs/expat-2.7.1.tar.bz2 -C src/libs
	tar -xjf src/libs/rnv-1.7.11.tar.bz2 -C src/libs
	cd src/libs/expat-2.7.1 && ./buildconf.sh
	cd src/libs/expat-2.7.1 && emconfigure ./configure \
	  --host=none-none-none --without-xmlwf --without-docbook
	cd src/libs/expat-2.7.1 && rm -f a.out* && emmake make
	mkdir -p src/libs/rnv-1.7.11/schema
	cp /usr/share/citation-style-language/schema/schemas/styles/*.rnc src/libs/rnv-1.7.11/schema/
	cd src/libs/rnv-1.7.11 && (emconfigure ./configure \
	  --with-expat-inc ../expat-2.7.1/lib/ \
	  --with-expat-lib ../expat-2.7.1/lib/.libs/ \
	  --host=wasm32-unknown-emscripten \
	  ac_cv_lib_expat_XML_SetDoctypeDeclHandler=yes || true)
	cd src/libs/rnv-1.7.11 && emconfigure ./configure \
	  --with-expat-inc=../expat-2.7.1/lib/ \
	  --with-expat-lib=../expat-2.7.1/lib/.libs/ \
	  --host=wasm32-unknown-emscripten
	cd src/libs/rnv-1.7.11 && emmake make CFLAGS="-O3 -sMODULARIZE -sEXPORT_ES6 \
	  -sEXPORT_NAME=RNV -sEXPORTED_RUNTIME_METHODS=FS \
	  -sWASM_ASYNC_COMPILATION=0 --embed-file schema/"
	mkdir -p dist
	mv src/libs/rnv-1.7.11/rnv dist/rnv.mjs
	mv src/libs/rnv-1.7.11/rnv.wasm dist/rnv.wasm
	cp csl-validator.mjs worker.mjs LICENSE.txt LICENSE_LIBS.txt dist/

override_dh_fixperms:
	dh_fixperms
	chmod -x debian/node-csl-validator-wasm/usr/share/nodejs/csl-validator-wasm/rnv.wasm

override_dh_auto_test:
	:
