#!/usr/bin/make -f
# -*- makefile -*-

include /usr/share/dpkg/pkg-info.mk

export DEB_BUILD_MAINT_OPTIONS = hardening=+all

LLHTTPVERSION = $(shell pkgjs-pjson . version)
export RELEASE = $(LLHTTPVERSION)
LLHTTPMAJORVERSION = $(shell pkgjs-pjson . version|perl -pe 's/\..*//')
export SONAME = libllhttp.so.$(LLHTTPVERSION)
export SONAMEALIAS = libllhttp.so.$(LLHTTPMAJORVERSION)
LIBLLHTTPVERSION = $(LLHTTPVERSION)~$(DEB_VERSION)

export PREFIX = debian/tmp/usr
export LIBDIR = debian/tmp/usr/lib/$(DEB_HOST_MULTIARCH)
export INCLUDEDIR = debian/tmp/usr/include

WASM_CFLAGS = --sysroot=/usr -target wasm32-unknown-wasi -fno-exceptions -fvisibility=hidden -mexec-model=reactor

WASM_LDFLAGS = -Wl,-error-limit=0 \
-Wl,-O3  \
-Wl,--lto-O3  \
-Wl,--strip-all  \
-Wl,--allow-undefined  \
-Wl,--export-dynamic  \
-Wl,--export-table  \
-Wl,--export=malloc  \
-Wl,--export=free  \
-Wl,--no-entry

WASM_OUT = build
WASM_SRC = $(WASM_OUT)/c/*.c  src/native/*.c
WASM_INC = -I$(WASM_OUT)
WASM_OPT_FLAGS = -O4 --converge --strip-debug --strip-dwarf --strip-producers --enable-bulk-memory

%:
	dh $@

execute_before_dh_auto_clean:
	dh_auto_clean --buildsystem=nodejs

execute_before_dh_auto_configure:
	dh_auto_configure --buildsystem=nodejs

execute_before_dh_auto_build:
	dh_auto_build --buildsystem=nodejs
	RELEASE=$(LLHTTPVERSION) make release all

	clang $(WASM_CFLAGS) $(WASM_LDFLAGS) $(WASM_SRC) $(WASM_INC) -o $(WASM_OUT)/llhttp.wasm
	wasm-opt $(WASM_OPT_FLAGS) -o $(WASM_OUT)/llhttp.wasm $(WASM_OUT)/llhttp.wasm

	clang $(WASM_CFLAGS) -msimd128 $(WASM_LDFLAGS) $(WASM_SRC) $(WASM_INC) -o $(WASM_OUT)/llhttp_simd.wasm
	wasm-opt $(WASM_OPT_FLAGS) --enable-simd -o $(WASM_OUT)/llhttp.wasm $(WASM_OUT)/llhttp.wasm
	
	dh_auto_configure --buildsystem=cmake -Drelease -- -DCMAKE_BUILD_TYPE=Release
	dh_auto_build --buildsystem=cmake -Drelease

execute_before_dh_auto_install:
	make install
	dh_auto_install --buildsystem=nodejs

execute_before_dh_auto_test:
	dh_auto_test --buildsystem=nodejs
