#!/usr/bin/make -f

include /usr/share/dpkg/architecture.mk
include /usr/share/dpkg/buildflags.mk
include /usr/share/dpkg/buildopts.mk
include /usr/share/dpkg/pkg-info.mk
include /usr/share/rustc/architecture.mk

export CFLAGS CXXFLAGS CPPFLAGS LDFLAGS
export DEB_HOST_RUST_TYPE DEB_HOST_GNU_TYPE
export DEB_CARGO_CRATE = rust_ast_gen_$(DEB_VERSION_UPSTREAM)
export CARGO_HOME = $(CURDIR)/debian/cargo_home
export CARGO_TARGET_DIR = $(CURDIR)/target

# The wrapper from dh-cargo points cargo at the Debian crates.
CARGO = /usr/share/cargo/bin/cargo
MANIFEST = --manifest-path rust-astgen/Cargo.toml
RELEASE = target/$(DEB_HOST_RUST_TYPE)/release
DOCDIR = debian/rust-astgen/usr/share/rust-astgen

%:
	dh $@

# Cargo.toml is in a subdirectory, so dh-cargo's build system does not apply.
override_dh_auto_configure:
	rm -f rust-astgen/Cargo.lock
	$(CARGO) prepare-debian debian/cargo_registry --link-from-system

override_dh_auto_build:
	$(CARGO) build --release $(MANIFEST) -p rust_ast_gen -p scala_bindings_gen

# The wrapper builds without dev-dependencies, which the tests need.
override_dh_auto_test:
ifeq (,$(filter nocheck,$(DEB_BUILD_OPTIONS)))
	/usr/bin/cargo test $(MANIFEST) --workspace --target $(DEB_HOST_RUST_TYPE) \
		$(if $(DEB_BUILD_OPTION_PARALLEL),-j$(DEB_BUILD_OPTION_PARALLEL))
endif

override_dh_auto_install:
	install -D -m 755 $(RELEASE)/rust_ast_gen debian/rust-astgen/usr/bin/rust_ast_gen
	install -d $(DOCDIR)
	$(RELEASE)/scala_bindings_gen --output $(DOCDIR)/RustNodeSyntax.scala --include-date false
	CARGO_BUILT_USING_TARGET_DIR=$(RELEASE) \
		/usr/share/cargo/bin/dh-cargo-built-using rust-astgen

override_dh_auto_clean:
	rm -rf target debian/cargo_home debian/cargo_registry rust-astgen/Cargo.lock
