#!/usr/bin/make -f

export ASSET_OUT_DIR=debian/tmp

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

# enable on 64-bit
execute_after_dh_auto_configure:
	echo 'lto="fat"' >> debian/cargo_home/config.toml
	echo 'codegen-units=1' >> debian/cargo_home/config.toml
	echo 'opt-level="z"' >> debian/cargo_home/config.toml
	cat debian/cargo_home/config.toml

%:
	dh $@ --buildsystem cargo --with bash-completion

export CARGO = /usr/share/cargo/bin/cargo
export CARGO_VENDOR_DIR = debian/rust-vendor
export CARGO_HOME = $(CURDIR)/debian/cargo_home

include /usr/share/rustc/architecture.mk
export DEB_HOST_RUST_TYPE DEB_HOST_GNU_TYPE

vendor:
	if QUILT_PATCHES=debian/patches quilt applied | grep vendor-remove-unused-deps ; then \
		echo "Detecting patch on vendor dir applied, aborting."; \
		exit 1; \
		fi
	# We need to have the dependencies removed in the top-level Cargo.toml or we vendor too much, and update them
	QUILT_PATCHES=debian/patches quilt applied | grep update-dependencies.patch || QUILT_PATCHES=debian/patches quilt push update-dependencies.patch
	rm -rf $(CARGO_VENDOR_DIR)
	# Deliberately don't use the wrapper, as it expects the configure step
	# to have occurred already.
	# If you have to modify the path here, don't forget to change the README.source doc
	# as well.
	env -i cargo-vendor-filterer --all-features  --tier 2  --platform '*-*-linux-gnu' --platform '*-*-linux-gnueabi' $(CARGO_VENDOR_DIR)
	# Remove the checksum files to allow us to patch the crates
	@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)
	find $(CARGO_VENDOR_DIR) -type f -name 'Cargo.toml.orig' -delete
	# Update include-binaries
	rm -f debian/source/include-binaries
	dpkg-source --include-binaries -b .
	# Update XS-Vendored-Sources-Rust field
	VENDORED_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 || true
	# Commit changes
	git add -f $(CARGO_VENDOR_DIR)
	git commit -m "Update vendored rust crates" || true
	git add debian/source/
	git commit -m "Update debian/source/include-binaries" || true
	git add debian/control
	git commit debian/control -m "Update XS-Vendored-Sources-Rust field" || true

override_dh_auto_configure:
	DEB_CARGO_CRATE=sequoia-sqv_$(shell dpkg-parsechangelog --show-field Version) \
					$(CARGO) prepare-debian $(CARGO_VENDOR_DIR)
#	/usr/share/cargo/bin/dh-cargo-vendored-sources
	dh_auto_configure

override_dh_clean:
	dh_clean
	rm -rf $(CARGO_HOME)
