#!/usr/bin/make -f

export DPKG_GENSYMBOLS_CHECK_LEVEL = 4

include /usr/share/rustc/architecture.mk
export DEB_HOST_RUST_TYPE DEB_HOST_GNU_TYPE
export PATH := /usr/share/cargo/bin:$(PATH)
export CARGO=/usr/share/cargo/bin/cargo
export CARGO_HOME=$(CURDIR)/debian/cargo_home
export CARGO_VENDOR_DIR = $(CURDIR)/debian/missing-sources
export DEB_CARGO_CRATE=$(DEB_SOURCE)_$(DEB_VERSION_UPSTREAM)
export DEB_BUILD_MAINT_OPTIONS=hardening=+bindnow

# Disable lto on 32-bit arches since it OOMs otherwise
ifeq ($(DEB_HOST_ARCH_BITS),32)
export DEB_BUILD_OPTIONS += optimize=-lto
endif

# Keep this in a Makefile variable to be overwritten by debian/tests/integration-tests
TEST_FLAGS = -Dtests=true -Dpython_tests=false -Dtest_skip_install=false

# qoi reftests fail on s390x
ifneq (,$(filter s390x,$(DEB_HOST_ARCH)))
  override TEST_FLAGS += -Dtest_skip_ext=qoi
endif

%:
	dh $@

execute_after_dh_auto_clean:
	rm -rf debian/cargo_registry

override_dh_auto_configure:
	$(CARGO) prepare-debian debian/cargo_registry --link-from-system
	rm -f Cargo.lock
	dh_auto_configure -- \
		-Dhost_arch="$(DEB_HOST_RUST_TYPE)" \
		-Dlibglycin-gtk4=$(if $(filter libglycin-gtk4-2-dev,$(shell dh_listpackages)),true,false) \
		$(TEST_FLAGS)

# Give the tests more time on slow arches
override_dh_auto_test:
	dh_auto_test -- --timeout-multiplier 5

override_dh_clean:
	dh_clean -Xdebian/missing-sources

execute_after_dh_auto_clean:
	rm -rf debian/cargo_registry

# Used by Ubuntu
vendor:
	dh_quilt_patch
	rm -rf $(CARGO_VENDOR_DIR)
	rm -rf .cargo
	$ cargo vendor-filterer --platform='*-*-linux-gnu' --platform '*-*-linux-gnueabi' \
	  --exclude-crate-path system-deps#src/tests/lib/libteststatic.a \
	  --exclude-crate-path system-deps#src/tests/uninstalled/lib/libtest.a \
	  --all-features \
	  $(CARGO_VENDOR_DIR)
	git add -f $(CARGO_VENDOR_DIR)
	git commit -m "Update vendored rust crates" || true
	git reset --hard && git clean -fdx

	env QUILT_PATCH_DIR=debian/missing-sources-patches dh_quilt_patch
	git add -f $(CARGO_VENDOR_DIR)
	git commit -m "Apply patches to vendored rust crates" || true
	git reset --hard && git clean -fdx

	gbp export-orig
	rm debian/source/include-binaries
	dpkg-source --include-binaries -b .
	git add debian/source/include-binaries
	git commit -m "Update debian/source/include-binaries" || true
	git reset --hard && git clean -fdx

	rm Cargo.toml
	VENDORED_SOURCES=$$(CARGO_VENDOR_DIR=debian/missing-sources/ /usr/share/cargo/bin/dh-cargo-vendored-sources 2>&1 | grep "^XS-Vendored-Sources-Rust:") \
	  && sed -i "s/^XS-Vendored-Sources-Rust:.*/$${VENDORED_SOURCES}/" debian/control || :
	git add debian/control
	git commit -m "Update XS-Vendored-Sources-Rust field" || true
	git checkout Cargo.toml
