#!/usr/bin/make -f

UPSTREAM_VERSION := $(shell dpkg-parsechangelog -S Version|cut -d- -f1)

# Vendoring setup
export CARGO_VENDOR_DIR = rust-vendor
export CARGO_HOME = $(CURDIR)/debian/cargo_home
VENDOR_TARBALL = rust-sudo-rs_$(UPSTREAM_VERSION).orig-$(CARGO_VENDOR_DIR).tar.xz

DEB_HOST_ARCH ?= $(shell dpkg-architecture -qDEB_HOST_ARCH)

%:
	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 cargo-vendor-filterer --all-features  --tier 2  --platform '*-*-linux-gnu' --platform '*-*-linux-gnueabi' $(CARGO_VENDOR_DIR)

vendor-deps: vendor-deps-cargo
	rm -r \
		$(CARGO_VENDOR_DIR)/*/tests
	# 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)

override_dh_auto_test:
	CARGO_HOME=$(CURDIR)/debian/cargo_home cargo test

ifeq ($(DEB_HOST_ARCH),i386)
override_dh_installman:
	echo "Skipping pandoc for i386"
else
override_dh_installman:
	pandoc -s -t man docs/man/su.1.md -o su-rs.1
	pandoc -s -t man docs/man/sudo.8.md  -o sudo-rs.8
	pandoc -s -t man docs/man/visudo.8.md -o visudo-rs.8
	dh_installman
endif

override_dh_auto_install:
	# /usr/bin/{su,sudo,visudo} are already used, install into /usr/lib/cargo/bin
	DEB_CARGO_INSTALL_PREFIX=/usr/lib/cargo dh_auto_install
	chmod 4755 debian/sudo-rs/usr/lib/cargo/bin/sudo

override_dh_dwz:
	# Don't do anything. fails because of the
	# https://github.com/rust-lang/rust/issues/66118

override_dh_auto_clean:
	rm -f *.1 *.8
	dh_auto_clean

