#!/usr/bin/make -f

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

ifneq (,$(filter parallel=%,$(DEB_BUILD_OPTIONS)))
	NUMJOBS = $(patsubst parallel=%,%,$(filter parallel=%,$(DEB_BUILD_OPTIONS)))
else
	NUMJOBS = 1
endif

CARGO_C_FLAGS = --release \
	--destdir=debian/tmp \
	--prefix=/usr \
	--libdir=/usr/lib/${DEB_HOST_MULTIARCH} \
	--offline \
	-v \
	-j $(NUMJOBS)

export CARGO_VENDOR_DIR = rust-vendor
export CARGO_HOME = $(CURDIR)/debian/cargo_home
VENDOR_TARBALL = rust-rav1e_$(DEB_VERSION_UPSTREAM).orig-$(CARGO_VENDOR_DIR).tar.xz

%:
	dh $@ --buildsystem cargo

vendor-tarball-quick-check:
	if [ -e ../$(VENDOR_TARBALL) ]; then echo "../$(VENDOR_TARBALL) already exists, bailing!"; exit 1; fi

vendor-deps-cargo:
	rm -rf $(CARGO_VENDOR_DIR)
	env -i PATH=$(PATH) cargo-vendor-filterer \
		--all-features \
		--tier 2 \
		--platform '*-*-linux-gnu' \
		--platform '*-*-linux-gnueabi' \
		--exclude-crate-path="*#tests" \
		--exclude-crate-path="*#test*data" \
		--exclude-crate-path="*#**/*.png" \
		--exclude-crate-path="*#**/*.a" \
		--exclude-crate-path="*#benches" \
		$(CARGO_VENDOR_DIR)

vendor-deps: vendor-deps-cargo
	# Remove the checksum files to allow us to patch the crates to remove extraneous dependencies
	for crate in $(CARGO_VENDOR_DIR)/*; do \
		sed -i 's/^{"files":.*"package":"\([a-z0-9]\+\)"}$$/{"files":{},"package":"\1"}/' $$crate/.cargo-checksum.json; \
		done
	# Cleanup temp files
	rm -rf $(CARGO_HOME)

vendor-tarball: vendor-tarball-quick-check vendor-deps
	tar --sort=name --mtime=@0 --owner=0 --group=0 --numeric-owner --pax-option=exthdr.name=%d/PaxHeaders/%f,delete=atime,delete=ctime -caf ../$(VENDOR_TARBALL) $(CARGO_VENDOR_DIR)

execute_after_dh_auto_build:
	CARGO_HOME=debian/cargo_home \
		/usr/share/cargo/bin/cargo cbuild $(CARGO_C_FLAGS)

execute_after_dh_auto_install:
	CARGO_HOME=debian/cargo_home \
		/usr/share/cargo/bin/cargo cinstall $(CARGO_C_FLAGS)

execute_after_dh_install:
	find debian -name Cargo.lock -delete
