#!/usr/bin/make -f
include /usr/share/dpkg/architecture.mk

# Always naming the Rust target lets `dpkg-buildpackage -a arm64` cross-build from amd64.
RUST_TYPE_amd64 = x86_64-unknown-linux-gnu
RUST_TYPE_arm64 = aarch64-unknown-linux-gnu
RUST_TARGET = $(RUST_TYPE_$(DEB_HOST_ARCH))

# The Makefile takes Rust from rustup, inside the build tree unless RUSTUP_HOME and CARGO_HOME name a rustup to reuse.
export RUSTUP_HOME ?= $(CURDIR)/debian/.rustup
export CARGO_HOME  ?= $(CURDIR)/debian/.cargo

export CARGO_TARGET_X86_64_UNKNOWN_LINUX_GNU_LINKER = $(DEB_BUILD_GNU_TYPE)-gcc
export CARGO_TARGET_AARCH64_UNKNOWN_LINUX_GNU_LINKER = aarch64-linux-gnu-gcc
export PKG_CONFIG = $(DEB_HOST_GNU_TYPE)-pkg-config
export PKG_CONFIG_ALLOW_CROSS = 1

# The paths of the build machine are not to go into the executables.
export RUSTFLAGS = --remap-path-prefix=$(CARGO_HOME)/registry/src=crates.io --remap-path-prefix=$(RUSTUP_HOME)=rustup --remap-path-prefix=$(CURDIR)=.

%:
	dh $@

override_dh_auto_configure:

override_dh_auto_build-arch:
	test -n "$(RUST_TARGET)" || { echo "unsupported DEB_HOST_ARCH: $(DEB_HOST_ARCH)" >&2; exit 1; }
	$(MAKE) all RUST_TARGET=$(RUST_TARGET)

override_dh_auto_build-indep:
	env -u CFLAGS -u CPPFLAGS -u CXXFLAGS -u LDFLAGS $(MAKE) web-tools
	env -u CFLAGS -u CPPFLAGS -u CXXFLAGS -u LDFLAGS $(MAKE) web

# `cargo test` would pull dependencies from the network; run it by hand.
override_dh_auto_test:

override_dh_auto_install-arch:
	$(MAKE) install DESTDIR=$(CURDIR)/debian/eydos-viewer PREFIX=/usr RUST_TARGET=$(RUST_TARGET)

override_dh_auto_install-indep:
	$(MAKE) install-web DESTDIR=$(CURDIR)/debian/eydos-viewer-web PREFIX=/usr

# The rustup downloaded stays, so the next build does not fetch it again; `rm -rf debian/.rustup debian/.cargo` drops it.
override_dh_auto_clean:
	$(MAKE) clean
	rm -f debian/rustup-init debian/rustup-init.sha256
	dh_clean
