#!/usr/bin/make -f
# output every command that modifies files on the build system.
#export DH_VERBOSE = 1

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

export DEB_BUILD_MAINT_OPTIONS = hardening=+all
include /usr/share/dpkg/buildflags.mk
export CFLAGS CXXFLAGS CPPFLAGS LDFLAGS
export DEB_HOST_RUST_TYPE DEB_HOST_GNU_TYPE

export CARGO_HOME = $(CURDIR)/debian/cargo_home
export DEB_CARGO_CRATE = mold_$(DEB_VERSION_UPSTREAM)
export CARGO = /usr/share/cargo/bin/cargo
# Where `mold -run` looks for mold-wrapper.so: $(MOLD_LIBDIR)/mold/
export MOLD_LIBDIR = /usr/lib

TARGET_DIR = target/$(DEB_HOST_RUST_TYPE)/release

%:
	dh $@

override_dh_auto_configure:
	# Cargo.lock pins crates.io versions and a git fork of mimalloc;
	# resolve against the crates packaged in Debian instead.
	[ -f Cargo.lock.orig ] || mv Cargo.lock Cargo.lock.orig
	$(CARGO) prepare-debian debian/cargo_registry --link-from-system

override_dh_auto_build:
	$(CARGO) build --release --workspace

override_dh_auto_test:
ifeq (,$(filter nocheck,$(DEB_BUILD_OPTIONS)))
	$(CARGO) test --release -p mold-cli --test integration
endif

override_dh_auto_install:
	install -D -m 0755 $(TARGET_DIR)/mold debian/mold/usr/bin/mold
	install -D -m 0644 $(TARGET_DIR)/mold-wrapper.so debian/mold/usr/lib/mold/mold-wrapper.so
	install -D -m 0644 docs/mold.1 debian/mold/usr/share/man/man1/mold.1

override_dh_auto_clean:
	$(CARGO) clean || true
	rm -rf debian/cargo_home debian/cargo_registry target
	[ ! -f Cargo.lock.orig ] || mv Cargo.lock.orig Cargo.lock

override_dh_dwz:
	# Don't do anything.
	# fails with
	# dwz: debian/mold/usr/bin/mold: elf_update failed
	# dwz: Too few files for multifile optimization

override_dh_gencontrol:
	/usr/share/cargo/bin/dh-cargo-built-using mold
	dh_gencontrol
