#!/usr/bin/make -f

# Defines DEB_*_RUST_TYPE triples
include /usr/share/rustc/architecture.mk

export CARGO_HOME = $(CURDIR)/debian/
export CARGO_VENDOR_DIR = $(CURDIR)/rust-vendor/
# Enable debug symbols to avoid debug-file-with-no-debug-symbols warning
export CARGO_PROFILE_RELEASE_DEBUG=1

CARGO_TARGET_DIR = $(CURDIR)/target
NUMJOBS = $(patsubst parallel=%,%,$(filter parallel=%,$(DEB_BUILD_OPTIONS)))
PKG_HWCTL = $(CURDIR)/debian/hwctl

%:
	dh $@ --buildsystem cargo

override_dh_auto_test:
	/usr/share/cargo/bin/cargo test --offline

override_dh_auto_install:
	# Since dh-cargo doesn't support installing multiple packages in a
	# workspace, we install the CLI tool using the same logic that is
	# implemented in the dh-cargo install function. See
	# https://salsa.debian.org/rust-team/dh-cargo/-/blob/5cc7f7b8/cargo.pm#L168-195
	env RUST_BACKTRACE=1 \
		CARGO_TARGET_DIR=$(CARGO_TARGET_DIR) \
		DESTDIR=$(CURDIR)/debian/hwctl \
		/usr/bin/cargo -Zavoid-dev-deps install \
		--verbose \
		--verbose \
		-j$(NUMJOBS) \
		--target $(DEB_HOST_RUST_TYPE) \
		--config 'profile.release.lto = "thin"' \
		--no-track \
		--path hwctl \
		--root $(CURDIR)/debian/hwctl/usr
	# Since we use vendored Rust code, it's required by ubuntu-mir to ship
	# Cargo.lock file in the package at /usr/share/doc/<pkgname>/Cargo.lock
	install -D -m 644 Cargo.lock $(PKG_HWCTL)/usr/share/doc/hwctl/Cargo.lock
	/usr/share/cargo/bin/dh-cargo-built-using hwctl

	# Delete generated via `cargo install` hidden files
	rm -f $(PKG_HWCTL)/.crates.toml
	rm -f $(PKG_HWCTL)/.crates2.json

	# Install the AppArmor profile
	mkdir -p $(PKG_HWCTL)/etc/apparmor.d/
	cp debian/usr.bin.hwctl $(PKG_HWCTL)/etc/apparmor.d/usr.bin.hwctl
	dh_apparmor -phwctl --profile-name=usr.bin.hwctl
