#!/usr/bin/make -f

export DEB_BUILD_MAINT_OPTIONS = hardening=+all
# The buildflags are injected by dh_auto_build, but the CFLAGS+=CPPFLAGS happens
# one layer outside, so the CPPFLAGS there are likely empty..
# By adding the include after the DEB_BUILD_MAINT_OPTIONS assignment and before
# the CFLAGS assignment, the variables are initialised in time.
include /usr/share/dpkg/buildflags.mk

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

# the makefile ignores CPPFLAGS, so add them to CFLAGS
export CFLAGS += $(CPPFLAGS)

# the Makefile uses INSTALL_PREFIX
export INSTALL_PREFIX = /usr
export DESTDIR = $(CURDIR)/debian/tmp

# the Makefile uses the cross-prefix in a non-standard way, so "enforce" it:
export CROSS_PREFIX=$(DEB_HOST_GNU_TYPE)-

COMMON_CMAKE_ARGS = -DQJS_LIB_NAME=qjs -DQJS_BUILD_LIBC=ON -DCMAKE_INSTALL_INCLUDEDIR=include/qjs

%:
	dh $@

override_dh_auto_configure:
	dh_auto_configure -Scmake -Bbuild-static -- $(COMMON_CMAKE_ARGS) -DBUILD_SHARED_LIBS=OFF
	dh_auto_configure -Scmake -Bbuild-shared -- $(COMMON_CMAKE_ARGS) -DBUILD_SHARED_LIBS=ON

override_dh_auto_build:
	mkdir -p unicode
	ln -sf /usr/share/unicode/*.txt unicode/
	ln -sf /usr/share/unicode/emoji/emoji-data.txt unicode/
	cp libunicode-table.h debian/
	make libunicode-table.h BUILD_DIR=build-static
	dh_auto_build -Scmake -Bbuild-static
	dh_auto_build -Scmake -Bbuild-shared

override_dh_auto_test:
	dh_auto_test -Scmake -Bbuild-static
	cd build-static && ./run-test262 -vv -c ../tests.conf
	dh_auto_test -Scmake -Bbuild-shared
	cd build-shared && ./run-test262 -vv -c ../tests.conf

override_dh_auto_install:
	dh_auto_install -Scmake -Bbuild-static
	dh_auto_install -Scmake -Bbuild-shared
	rm -fv debian/tmp/usr/share/doc/quickjs/LICENSE

execute_before_dh_installman:
	perl -ne 'print if /^## `qjs`/ .. /^###/' docs/docs/cli.md \
		| sed -e 's/^## `qjs`/## qjs(1)/' -e 's/^## /# /' \
		| head -n -1 \
		| ronn --roff --manual 'QuickJS-NG $(DEB_VERSION_UPSTREAM)' --pipe > debian/qjs.1
	perl -ne 'print if /^## `qjsc`/ .. (!/^## `qjsc`/ and (/^##/ or eof))' docs/docs/cli.md \
		| sed -e 's/^## `qjsc`/## qjsc(1)/' -e 's/^## /# /' \
		| head -n -1 \
		| ronn --roff --manual 'QuickJS-NG $(DEB_VERSION_UPSTREAM)' --pipe > debian/qjsc.1

execute_after_dh_clean:
	- mv -f debian/libunicode-table.h .
