#!/usr/bin/make -f

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

export CARGO = /usr/share/cargo/bin/cargo
export CARGO_VENDOR_DIR = rust-vendor
export CARGO_HOME = $(CURDIR)/debian/cargo_home

VENDOR_TARBALL = rust-ntpd_$(DEB_VERSION_UPSTREAM).orig-$(CARGO_VENDOR_DIR).tar.xz
CARGO_VENDOR_FILTERER = cargo-vendor-filterer

%:
	dh $@ --buildsystem cargo

debian/copyright: debian/copyright.header debian/copyright.in.d/* debian/bin/merge-copyright debian/rules
	debian/bin/merge-copyright \
		--header debian/copyright.header \
		--in-dir debian/copyright.in.d \
		-o debian/copyright.new
	cme check dpkg-copyright -file debian/copyright.new
	wrap-and-sort -ast -f debian/copyright.new
	mv debian/copyright.new debian/copyright

vendor-tarball-quick-check:
	if [ -e ../$(VENDOR_TARBALL) ]; then echo '../$(VENDOR_TARBALL) already exists, bailing.'; exit 1; fi

vendor-deps-cargo:
	rm -rf $(CARGO_VENDOR_DIR)
	env -i RUST_BACKTRACE=full $(CARGO_VENDOR_FILTERER) \
		--all-features \
		--tier 2 \
		--exclude-crate-path 'aws-lc-sys#aws-lc' \
		--exclude-crate-path 'aws-lc-sys#src' \
		--exclude-crate-path 'aws-lc-sys#generated-include' \
		--exclude-crate-path 'aws-lc-sys#builder' \
		--exclude-crate-path 'aws-lc-rs#src' \
		--exclude-crate-path 'ring#pregenerated' \
		--exclude-crate-path 'ring#crypto' \
		--exclude-crate-path 'ring#third_party' \
		--exclude-crate-path 'openssl-src#openssl' \
		--exclude-crate-path 'tracing#test-macros' \
		--exclude-crate-path 'vcpkg#test-data' \
		--exclude-crate-path '*#tests' \
		--exclude-crate-path '*#examples' \
		--exclude-crate-path '*#benches' \
		--platform '*-*-linux-gnu' \
		--platform '*-*-linux-gnueabi' \
		$(CARGO_VENDOR_DIR)

vendor-deps: vendor-deps-cargo
	# winnow uses this example file as documentation, included via `include_str!`.
	# To avoid having to modify the cargo-vendor-filterer invocation to include
	# this example, just create an empty stub.
	mkdir -p $(CARGO_VENDOR_DIR)/winnow/examples/css
	touch $(CARGO_VENDOR_DIR)/winnow/examples/css/parser.rs

	for checksum in $(CARGO_VENDOR_DIR)/*/.cargo-checksum.json; do \
		echo $$checksum; sed -i 's/^{"files":.*"package":"\([a-z0-9]\+\)"}$$/{"files":{},"package":"\1"}/' $$checksum; \
	done
	# Cleanup temp files
	rm -rf $(CARGO_HOME)

vendor-tarball: vendor-tarball-quick-check vendor-deps
	tar --sort=name \
		--mtime=@$(SOURCE_DATE_EPOCH) \
		--owner=0 \
		--group=0 \
		--format=gnu \
		--auto-compress \
		--create \
		--file ../$(VENDOR_TARBALL) \
		$(CARGO_VENDOR_DIR)

override_dh_auto_configure:
	DEB_CARGO_CRATE=rust-ntpd_$(DEB_VERSION) $(CARGO) prepare-debian $(CARGO_VENDOR_DIR)
	/usr/share/cargo/bin/dh-cargo-vendored-sources
	dh_auto_configure

override_dh_auto_install:
	DESTDIR=debian/tmp dh_auto_install
	dh_apparmor -pntpd-rs --profile-name=usr.bin.ntp-daemon

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