#!/usr/bin/make -f

export ASSET_OUT_DIR=debian/tmp

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

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

# Configure dh_quilt_patch for applying vendor patches
# This allows the debian/rust-vendor/ to be patched without dpkg-source issues
export QUILT_PATCH_DIR=debian/patches/rust-vendor
export QUILT_PC=debian/rust-vendor/.pc

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

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
	QUILT_PATCHES=debian/patches quilt applied | grep remove-dependencies.patch || QUILT_PATCHES=debian/patches quilt push remove-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 Cargo.lock
	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-sq_$(shell dpkg-parsechangelog --show-field Version) \
					$(CARGO) prepare-debian $(CARGO_VENDOR_DIR)
	/usr/share/cargo/bin/dh-cargo-vendored-sources
	dh_quilt_patch
	dh_auto_configure

override_dh_clean:
	dh_clean
	rm -rf $(CARGO_HOME)
