#!/usr/bin/make -f

export DEB_BUILD_MAINT_OPTIONS=hardening=+all
export DEB_CPPFLAGS_MAINT_APPEND = -D_GNU_SOURCE
export CARGO = /usr/share/cargo/bin/cargo
export CARGO_VENDOR_DIR = vendor
export CARGO_HOME = $(CURDIR)/debian/cargo_home
export PKG_CONFIG_PATH = /usr/lib/x86_64-linux-gnu/pkgconfig/

DPKG_EXPORT_BUILDFLAGS = 1
include /usr/share/dpkg/default.mk
include /usr/share/rustc/architecture.mk
export DEB_HOST_RUST_TYPE DEB_HOST_GNU_TYPE

VENDOR_TARBALL = asusctl_$(DEB_VERSION_UPSTREAM).orig-$(CARGO_VENDOR_DIR).tar.xz

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

vendor-deps:
	if QUILT_PATCHES=debian/patches quilt applied | grep vendor-remove-unused-deps ; then \
		echo "Detecting patch on vendor dir applied, aborting."; \
		exit 1; \
	fi
	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.
	cargo vendor --manifest-path rust/Cargo.toml $(CARGO_VENDOR_DIR)
	# Remove some crates that aren't useful for us and take up a lot of space
	rm -r \
		$(CARGO_VENDOR_DIR)/winapi \
		$(CARGO_VENDOR_DIR)/winapi-* \
		$(CARGO_VENDOR_DIR)/windows-* \
		$(CARGO_VENDOR_DIR)/windows_* \
		$(CARGO_VENDOR_DIR)/libloading/tests/*.dll \
		# End of list
	# Remove the C sources from the binding crates, we're using the system libs
	rm -r \
		$(CARGO_VENDOR_DIR)/libz-sys/src/zlib \
		$(CARGO_VENDOR_DIR)/libz-sys/src/zlib-ng \
		$(CARGO_VENDOR_DIR)/curl-sys/curl \
		# End of list
	# Remove unused and undesirable data files (e.g. test data for vendored crates)
	rm -r \
		$(CARGO_VENDOR_DIR)/vcpkg/test-data \
		$(CARGO_VENDOR_DIR)/*/tests \
		# End of list
	# Remove the checksum files to allow us to patch the crates to remove extraneous dependencies
	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)

vendor-tarball: vendor-tarball-sanity-check vendor-deps
	tar -caf ../$(VENDOR_TARBALL) $(CARGO_VENDOR_DIR)

%:
	dh $@

override_dh_auto_configure:
	tar -xvf ../$(VENDOR_TARBALL) -C .
	DEB_CARGO_CRATE=asusctl_$(shell dpkg-parsechangelog --show-field Version) \
	$(CARGO) prepare-debian $(CARGO_VENDOR_DIR)
	/usr/share/cargo/bin/dh-cargo-vendored-sources
	dh_auto_configure

override_dh_install:
	dh_install

override_dh_installdocs:
	mv CHANGELOG.md changelog || true
	dh_installdocs

override_dh_fixperms:
	dh_fixperms

override_dh_auto_clean:
	dh_auto_clean -- $(options)

override_dh_auto_build:
	dh_auto_build -- $(options)

override_dh_auto_install:
	HAVE_INITRAMFS=1 HAVE_DRACUT=1 dh_auto_install -- $(options)

override_dh_builddeb:
	dh_builddeb

override_dh_clean:
	dh_clean
	rm -rf $(CARGO_HOME)
