#!/usr/bin/make -f

export DEB_BUILD_MAINT_OPTIONS = hardening=+all

include /usr/share/dpkg/architecture.mk
include /usr/share/dpkg/buildflags.mk
include /usr/share/dpkg/pkg-info.mk
include /usr/share/rustc/architecture.mk
export CFLAGS CXXFLAGS CPPFLAGS LDFLAGS
export DEB_HOST_RUST_TYPE DEB_HOST_GNU_TYPE

# Use the debian cargo wrapper, it is only active if CARGO_HOME ends in
# debian/cargo_home and injects Debian's RUSTFLAGS, DEB_BUILD_OPTIONS
# handling and the system crate registry.
export CARGO_HOME = $(CURDIR)/debian/cargo_home
export DEB_CARGO_CRATE = idlc_$(DEB_VERSION_UPSTREAM)
CARGO = /usr/share/cargo/bin/cargo
IDLC = $(CURDIR)/target/$(DEB_HOST_RUST_TYPE)/release/idlc

%:
	dh $@

override_dh_auto_configure:
	# Upstream's lockfiles pin crates.io versions, resolve against the
	# Debian registry instead.
	rm -f Cargo.lock tests/Cargo.lock
	$(CARGO) prepare-debian debian/cargo_registry --link-from-system

override_dh_auto_build:
	$(CARGO) build --release
	# Generate Static-Built-Using before the test builds add dev-dependencies,
	# stash it as dh_prep removes debian/*.substvars before dh_auto_install
	/usr/share/cargo/bin/dh-cargo-built-using mink-idl-compiler
	mv debian/mink-idl-compiler.substvars debian/cargo-built-using.substvars

override_dh_auto_test:
	$(CARGO) test --release
	# Integration tests: compile and run C/C++/Rust code generated by idlc
	cd tests && IDLC=$(IDLC) CARGO_TARGET_DIR=$(CURDIR)/target/idlc_test \
	  $(CARGO) test --release

override_dh_auto_install:
	install -D -m 0755 $(IDLC) debian/tmp/usr/bin/mink-idlc
	cat debian/cargo-built-using.substvars >> debian/mink-idl-compiler.substvars

	mkdir -p debian/tmp/usr/share/man/man1
	help2man --no-info --version-string=$(DEB_VERSION_UPSTREAM) \
	  --name="compiler for the Mink Interface Definition Language" \
	  --output=debian/tmp/usr/share/man/man1/mink-idlc.1 \
	  debian/tmp/usr/bin/mink-idlc

override_dh_auto_clean:
	rm -rf target tests/target debian/cargo_home debian/cargo_registry \
	  debian/cargo-built-using.substvars
