#!/usr/bin/make -f

export DH_VERBOSE = 1
export CARGO_HOME = $(CURDIR)/debian/cargo_home
# Use the system libssl-dev; do not let openssl-sys vendor/build OpenSSL from
# source (it does not recognise all Rust target triples, e.g. riscv64a23).
export OPENSSL_NO_VENDOR = 1
export ZSTD_SYS_USE_PKG_CONFIG = 1

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

CARGO_FEATURE_LIST := kvm,io_uring
ifneq ($(DEB_HOST_ARCH),riscv64)
CARGO_FEATURE_LIST := $(CARGO_FEATURE_LIST),fw_cfg
endif
CARGO_FEATURES := --no-default-features --features $(CARGO_FEATURE_LIST)

%:
	dh $@

override_dh_auto_configure:
	mkdir -p $(CARGO_HOME)
	mkdir -p .cargo
	cp debian/cargo-config.toml .cargo/config.toml

override_dh_auto_build:
	cargo build --release --offline $(CARGO_FEATURES) \
		--package cloud-hypervisor

override_dh_auto_test:

override_dh_auto_install:
	install -D -m 0755 target/release/cloud-hypervisor \
		debian/cloud-hypervisor/usr/bin/cloud-hypervisor
	install -D -m 0755 target/release/ch-remote \
		debian/cloud-hypervisor/usr/bin/ch-remote

override_dh_auto_clean:
	cargo clean 2>/dev/null || true
	rm -rf .cargo $(CARGO_HOME)

# dh_clean removes *.orig files (treating them as patch artifacts), but
# vendored crates ship Cargo.toml.orig and cargo verifies checksums for
# every file listed in .cargo-checksum.json.  Exclude vendor/ from the
# cleanup so those files survive into the build.
override_dh_clean:
	dh_clean -Xvendor

override_dh_dwz:
override_dh_strip:
	strip --strip-unneeded --remove-section=.comment --remove-section=.note \
		debian/cloud-hypervisor/usr/bin/cloud-hypervisor \
		debian/cloud-hypervisor/usr/bin/ch-remote

# Generate the vendored Rust dependencies tarball.
# Usage: debian/rules vendor-tarball
VENDOR_TARBALL = ../$(DEB_SOURCE)_$(DEB_VERSION_UPSTREAM).orig-vendor.tar.xz

vendor-tarball:
	rm -rf vendor
	cargo vendor-filterer \
		--platform=x86_64-unknown-linux-gnu \
		--platform=x86_64-unknown-linux-musl \
		--platform=aarch64-unknown-linux-gnu \
		--platform=aarch64-unknown-linux-musl \
		--platform=riscv64gc-unknown-linux-gnu \
		--exclude-crate-path='*#tests' \
		--exclude-crate-path='linux-loader#src/loader/**/*.bin' \
		--exclude-crate-path='*#**/*.png' \
		--exclude-crate-path='*#**/*.jpg' \
		--exclude-crate-path='*#**/*.dtb' \
		--exclude-crate-path='libssh2-sys#libssh2' \
		--exclude-crate-path='openssl-src#openssl' \
		--exclude-crate-path='zstd-sys#zstd' \
		--exclude-crate-path='libz-sys#src'
	tar cJf $(VENDOR_TARBALL) vendor/
	rm -rf vendor
	@echo "Created $(VENDOR_TARBALL)"

.PHONY: vendor-tarball
