#!/usr/bin/make -f

# mozjs' build process does not seem to be compatible with other shells
# like zsh
export SHELL = /bin/sh

export DEB_BUILD_MAINT_OPTIONS = hardening=+all
DPKG_EXPORT_BUILDFLAGS = 1
include /usr/share/dpkg/buildflags.mk

include /usr/share/dpkg/architecture.mk

PARALLEL = $(or $(subst parallel=,-j,$(filter parallel=%,${DEB_BUILD_OPTIONS})), -j$(shell getconf _NPROCESSORS_ONLN))

%:
	dh $@

override_dh_auto_clean:
	# cleanup cruft from unpacking embedded libraries
	rm -rf libraries/source/cxxtest-*/cxxtest-*/
	rm -rf libraries/source/fcollada/fcollada-*/
	rm -rf libraries/source/nvtt/nvtt-*/
	rm -rf libraries/source/premake-core/premake-*/
	rm -rf libraries/source/spidermonkey/mozjs-*/
	rm -rf libraries/source/spirv-reflect/SPIRV-Reflect-vulkan-sdk-*/
	rm  -f libraries/source/*/.already-built
	rm -rf libraries/source/*/bin/
	rm -rf libraries/source/*/include/
	rm -rf libraries/source/*/include-*/
	rm -rf libraries/source/*/lib/
	# cleanup all other cruft
	find binaries/system/ -type f ! -name readme.txt -delete
	rm -f build/premake/.*.tmp
	rm -rf build/workspaces/gcc
	find libraries -name \*.pyc -delete
	find libraries -depth -name __pycache__ -exec rm -rf {} +
	rm -f source/ps/tests/stub_impl_hack.cpp
	dh_auto_clean

override_dh_auto_build:
	libraries/build-source-libs.sh \
		--with-system-cxxtest \
		$(PARALLEL)
	build/workspaces/update-workspaces.sh \
		--bindir=/usr/games \
		--libdir=/usr/lib/games/0ad \
		--datadir=/usr/share/games/0ad \
		--with-system-cxxtest \
		--with-lto \
		$(PARALLEL)
	
	$(MAKE) config=release verbose=1 -C build/workspaces/gcc \
		$(PARALLEL)

override_dh_auto_test:
	# Note: Avoid running tests from root dir of build, otherwise certain
	# tests (i.e. in testsuite MeshManager) may not work as intended and
	# create spurious directories above root dir (../data/mods).
	# Also avoid running tests on non-amd64 due to testsuite flakiness.
ifeq (amd64, $(DEB_HOST_ARCH))
	cd binaries/system/ && LD_LIBRARY_PATH=. ./test
endif

override_dh_auto_install:
	install -Dm 0755 build/resources/0ad.sh $(CURDIR)/debian/tmp/usr/games/0ad
	dh_auto_install

override_dh_makeshlibs:
	dh_makeshlibs -Xusr/lib/games/0ad

override_dh_dwz:
	dh_dwz -Xlibmozjs115-release.so -Xlibmozjs115-debug.so
