#!/usr/bin/make -f

# plugins/ are WebAssembly guest programs (separate modules, need go-pdk).
export DH_GOLANG_EXCLUDES := ^(github.com/extism/go-sdk/)?plugins(/|$$)
export DH_GOLANG_INSTALL_EXTRA := extism-runtime.wasm extism-runtime.wasm.version testdata

# The kernel crate has no dependencies, so rustc builds it without cargo,
# with the release profile cargo would use.
KERNEL := extism/kernel
KBUILD := debian/kernel
RUSTC := rustc --edition=2021 --target=wasm32-unknown-unknown \
	-C opt-level=3 -C codegen-units=16 -C linker=wasm-ld \
	--remap-path-prefix=$(CURDIR)=. \
	--cfg 'feature="default"' --cfg 'feature="bounds-checking"'
RUST_STD := $(shell dpkg-query -f '$${source:Package} (= $${source:Version})' -W libstd-rust-dev-wasm32)

%:
	dh $@ --builddirectory=debian/_build --buildsystem=golang --with=golang

# Build extism-runtime.wasm the way extism/kernel/build.sh does.
execute_before_dh_auto_configure:
	mkdir -p $(KBUILD)
	$(RUSTC) --crate-type=lib --crate-name=extism_runtime_kernel \
		-o $(KBUILD)/libextism_runtime_kernel.rlib $(KERNEL)/src/lib.rs
	$(RUSTC) --crate-type=bin --crate-name=extism_runtime \
		--extern extism_runtime_kernel=$(KBUILD)/libextism_runtime_kernel.rlib \
		-o $(KBUILD)/extism-runtime.wasm $(KERNEL)/src/bin/extism-runtime.rs
	wasm-tools parse $(KERNEL)/extism-context.wat -o $(KBUILD)/extism-context.wasm
	wasm-merge --enable-reference-types $(KBUILD)/extism-runtime.wasm runtime \
		$(KBUILD)/extism-context.wasm context -o extism-runtime.wasm
	wasm-strip extism-runtime.wasm
	wasm-tools parse testdata/kernel.wat -o testdata/kernel.wasm

execute_after_dh_auto_clean:
	rm -rf $(KBUILD) extism-runtime.wasm testdata/kernel.wasm

# Upstream's tests load prebuilt plugins from wasm/, excluded from the orig
# because their sources need TinyGo and go-pdk, or are not published. Only
# the tests from debian/patches run; they use the kernel built above.
override_dh_auto_test:
	dh_auto_test -- -run '^TestDebianKernel'

override_dh_gencontrol:
	dh_gencontrol -- '-VextismKernel:Static-Built-Using=$(RUST_STD)'
