#!/usr/bin/make -f
include /usr/share/dpkg/architecture.mk
include /usr/share/dpkg/buildflags.mk
include /usr/share/rustc/architecture.mk
export CFLAGS CXXFLAGS CPPFLAGS LDFLAGS
export DEB_HOST_RUST_TYPE DEB_HOST_GNU_TYPE
export CARGO_PROFILE_RELEASE_DEBUG=true
export SKIP_UTILS=stdbuf

# Use lld whenever it is available: it links the big multicall binary much
# faster than GNU ld. Fall back to the default linker on arches where lld is
# not installed. Always ask the linker to print its version banner (-Wl,-v)
# so the build log records which linker actually ran.
LLD := $(shell command -v ld.lld 2>/dev/null)
ifneq ($(LLD),)
export RUSTFLAGS = -C link-arg=-fuse-ld=lld -C link-arg=-Wl,-v
else
export RUSTFLAGS = -C link-arg=-Wl,-v
endif

# Fat LTO + 1 codegen unit + full debuginfo of the giant multicall crate is
# fatal on some arches: s390x hits the 150min buildd timeout, 32-bit arches OOM
# on the ~3GB address space ("rustc-LLVM ERROR: out of memory"). Set the cargo
# profile env overrides so they apply to every cargo invocation (build, test,
# install), unlike a Cargo.toml sed that only wraps one step.
ifeq ($(DEB_HOST_ARCH),s390x)
export CARGO_PROFILE_RELEASE_LTO = false
export CARGO_PROFILE_RELEASE_CODEGEN_UNITS = 16
export CARGO_PROFILE_RELEASE_DEBUG = 1
endif
ifeq ($(DEB_HOST_ARCH_BITS),32)
export CARGO_PROFILE_RELEASE_LTO = thin
export CARGO_PROFILE_RELEASE_CODEGEN_UNITS = 16
export CARGO_PROFILE_RELEASE_DEBUG = 1
endif
VERSION := $(shell dpkg-parsechangelog -S Version|sed -e "s|.*~\(.*\)-.*|\1|g")
UPSTREAM_VERSION := $(shell dpkg-parsechangelog -S Version|cut -d- -f1)

# Build a multicall binary instead of multiple binaries
# to reduce the storage footprint
export MULTICALL = y

# Vendoring setup.
# The crates are NOT part of the upstream tarball (which is the pristine
# GitHub tag): they are vendored into debian/rust-vendor by the 'vendor'
# target below and shipped in the .debian.tar. This is what the Ubuntu
# package does, so the two stay mergeable.
export CARGO_VENDOR_DIR = debian/rust-vendor
export CARGO_HOME = $(CURDIR)/debian/cargo_home

# Configure dh_quilt_patch for applying vendor patches.
# This allows debian/rust-vendor/ to be patched without dpkg-source issues.
export QUILT_PATCH_DIR = debian/patches/rust-vendor
export QUILT_PC = debian/rust-vendor/.pc

%:
	dh $@ --buildsystem cargo

override_dh_auto_configure:
	# The translations live in a separate upstream repository and are shipped
	# as a component tarball; without them the package would silently build
	# without any localisation.
	@if [ ! -d l10n/src ]; then \
		echo "Error: l10n translations not found! Run 'uscan' to download the l10n tarball." >&2; \
		exit 1; \
	fi
	# The tldr examples embedded in the manpages (see improve-man.diff) come
	# from the tldr-pages release shipped in debian/, since the upstream
	# tarball does not contain it and the build has no network access.
	cp debian/tldr.zip docs/tldr.zip
	dh_auto_configure
	# Debian's dh-cargo hardcodes "prepare-debian debian/cargo_registry
	# --link-from-system" in its configure step, while Ubuntu's honours
	# CARGO_VENDOR_DIR. Point cargo back at our vendor directory afterwards
	# so the build uses the same crates on both distributions.
	DEB_CARGO_CRATE=coreutils_$(VERSION) /usr/share/cargo/bin/cargo prepare-debian $(CARGO_VENDOR_DIR)
	# dh-cargo-vendored-sources only exists in Ubuntu's dh-cargo; it checks
	# XS-Vendored-Sources-Rust against the vendor directory. Run it when it
	# is there so the Ubuntu build behaves exactly as before.
	[ ! -x /usr/share/cargo/bin/dh-cargo-vendored-sources ] || /usr/share/cargo/bin/dh-cargo-vendored-sources
	dh_quilt_patch

.PHONY: vendor

# Maintainer-side target: regenerate debian/rust-vendor. Needs
# cargo-vendor-filterer, which is not packaged in Debian:
#   cargo install cargo-vendor-filterer
# Run it after every new upstream import, then commit the result.
vendor:
	rm -rf $(CARGO_VENDOR_DIR)
	# Deliberately don't use the wrapper, as it expects the configure step
	# to have occurred already.
	# If you have to modify the path here, don't forget to change the
	# README.source doc as well.
	# PATH/HOME are kept so that a cargo-vendor-filterer installed with
	# 'cargo install' is found and can reach the registry cache; everything
	# else (CARGO_HOME, CARGO_VENDOR_DIR, ...) is deliberately cleared.
	env -i PATH="$$PATH" HOME="$$HOME" cargo-vendor-filterer --all-features --tier 2 --platform '*-*-linux-gnu' --platform '*-*-linux-gnueabi' $(CARGO_VENDOR_DIR)
	# Remove the checksum files to allow us to patch the crates
	@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)
	# Update include-binaries
	rm -f debian/source/include-binaries
	dpkg-source --include-binaries -b .
	# Update XS-Vendored-Sources-Rust field. Ubuntu generates it with
	# dh-cargo-vendored-sources; that helper is not in Debian's dh-cargo, so
	# read the crate names out of the vendor directory instead.
	python3 debian/update-vendored-sources-field.py
	# Commit changes
	git add -f $(CARGO_VENDOR_DIR)
	git commit -m "Update vendored rust crates" || true
	git add debian/source/
	git commit -m "Update debian/source/include-binaries" || true
	git add debian/control
	git commit debian/control -m "Update XS-Vendored-Sources-Rust field" || true

override_dh_auto_test:
ifeq ($(DEB_HOST_ARCH),s390x)
	# The release test build (every util + every test) is what actually hits
	# the buildd inactivity timeout on s390x. Tests are non-gating here (||true)
	# anyway, so skip them and rely on the other arches for coverage.
	@echo "Skipping the test suite on s390x to stay under the buildd timeout"
else
	# for now, don't fail the build if tests are failing
	CARGO_HOME=$(CURDIR)/debian/cargo_home make PROFILE=release MULTICALL=$(MULTICALL) test||true
endif

override_dh_auto_install:
# The vendor directory is prepared once in override_dh_auto_configure.
# LTO/debuginfo/codegen are handled globally via CARGO_PROFILE_RELEASE_* env
# overrides at the top of this file, so no Cargo.toml editing is needed here.
	CARGO_HOME=$(CURDIR)/debian/cargo_home DESTDIR=$(CURDIR)/debian/tmp/ make SELINUX_ENABLED=1 PROFILE=release MULTICALL=$(MULTICALL) install
# Create the symlink early to be able to generate the manpages
	cd debian/tmp/usr/share/zsh/site-functions && mkdir rust-coreutils && chmod -x _* && mv _* rust-coreutils
	cd debian/tmp/usr/share/bash-completion/completions/ && chmod -x rust-*
	cd debian/tmp/usr/share/fish/vendor_completions.d/ && chmod -x *.fish
	cd debian/tmp/usr/bin && mv rust-coreutils coreutils && rm rust-*
#	cd debian/tmp/usr/share/fish/vendor_completions.d && for f in *fish; do mv $$f rust-$$f; done
	dh_link

override_dh_missing:
	dh_missing --fail-missing

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

execute_after_dh_auto_configure:
	# Log the toolchain and linker up front, on every arch, so the build log
	# always records which linker was used - even if a later step times out
	# before any link runs. The leading '-' keeps the build going on the rare
	# arch where ld.lld is absent (we fall back to the default linker there).
	rustc --version --verbose
	-ld.lld --version
	-ld --version | head -n1

override_dh_clean:
	dh_quilt_unpatch
	rm -f Cargo.toml.orig docs/tldr.zip
	dh_clean --exclude=Cargo.toml.orig --exclude=config.guess

override_dh_update_autotools_config:
	# don't do anything - impact vendoring otherwise
