#!/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)-

%:
	dh $@

override_dh_auto_configure:
	cmake -B build-static -DQJS_LIB_NAME=qjs -DBUILD_SHARED_LIBS=OFF -DQJS_BUILD_LIBC=ON -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=/usr -DCMAKE_INSTALL_INCLUDEDIR=include/qjs
	cmake -B build-shared -DQJS_LIB_NAME=qjs -DBUILD_SHARED_LIBS=ON -DQJS_BUILD_LIBC=ON -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=/usr -DCMAKE_INSTALL_INCLUDEDIR=include/qjs

execute_before_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

override_dh_auto_build:
	cmake --build build-static
	cmake --build build-shared

override_dh_auto_install:
	cmake --build build-static --target install
	cmake --build build-shared --target install
	ln -s qjs.pc $(DESTDIR)/usr/lib/$(DEB_HOST_MULTIARCH)/pkgconfig/quickjs-ng.pc
	ln -s qjs $(DESTDIR)/usr/lib/$(DEB_HOST_MULTIARCH)/cmake/quickjs-ng

execute_after_dh_auto_clean:
	rm -rf build*

execute_before_dh_installman:
	perl -ne 'print if /^## `qjs`/ .. /^###/' docs/docs/cli.md \
		| sed 's/^## /# /' \
		| head -n -1 \
		| marked-man --version $(DEB_VERSION_UPSTREAM) \
		> debian/qjs.1
	perl -ne 'print if /^## `qjsc`/ .. (!/^## `qjsc`/ and (/^##/ or eof))' docs/docs/cli.md \
		| sed 's/^## /# /' \
		| head -n -1 \
		| marked-man --version $(DEB_VERSION_UPSTREAM) \
		> debian/qjsc.1

execute_after_dh_clean:
	rm -f debian/qjs*.1
	rm -rf unicode
	- mv -f debian/libunicode-table.h .

execute_before_dh_missing:
	rm -f debian/tmp/usr/share/doc/quickjs/LICENSE
