TARGET_DIR = ./rust/target
LIBDIR = $(TARGET_DIR)/@LIBDIR@
STATLIB = $(LIBDIR)/libsmoothbp.a
PKG_LIBS = -L$(LIBDIR) -lsmoothbp

all: $(SHLIB) rust_clean

.PHONY: $(STATLIB)

$(SHLIB): $(STATLIB)

CARGOTMP = $(CURDIR)/.cargo
VENDOR_DIR = $(CURDIR)/vendor


# RUSTFLAGS appends --print=native-static-libs to ensure that 
# the correct linkers are used. Use this for debugging if need. 
#
# CRAN note: Cargo and Rustc versions are reported during
# configure via tools/msrv.R.
#
# If a vendor directory exists, it is used for offline compilation. Otherwise if
# vendor.tar.xz exists, it is unzipped and used for offline compilation.
$(STATLIB):

	if [ -d ./vendor ]; then \
		echo "=== Using offline vendor directory ==="; \
		mkdir -p $(CARGOTMP) && \
		printf '[source.crates-io]\nreplace-with = "vendored-sources"\n\n[source.vendored-sources]\ndirectory = "$(VENDOR_DIR)"\n' > $(CARGOTMP)/config.toml; \
	elif [ -f ./rust/vendor.tar.xz ]; then \
		echo "=== Using offline vendor tarball ==="; \
		tar xf rust/vendor.tar.xz && \
		mkdir -p $(CARGOTMP) && \
		printf '[source.crates-io]\nreplace-with = "vendored-sources"\n\n[source.vendored-sources]\ndirectory = "$(VENDOR_DIR)"\n' > $(CARGOTMP)/config.toml; \
	fi

	export CARGO_HOME=$(CARGOTMP) && \
	export PATH="$(PATH):$(HOME)/.cargo/bin" && \
	@PANIC_EXPORTS@RUSTFLAGS="$(RUSTFLAGS) --print=native-static-libs" cargo build @CRAN_FLAGS@ --lib @PROFILE@ --manifest-path=./rust/Cargo.toml --target-dir $(TARGET_DIR) @TARGET@

	export CARGO_HOME="$(CARGOTMP)" && \
	export PATH="$(PATH):$(HOME)/.cargo/bin" && \
	cargo run @CRAN_FLAGS@ @PROFILE@ --bin document --manifest-path=./rust/Cargo.toml --target-dir $(TARGET_DIR) @TARGET@

	# Always clean up CARGOTMP
	rm -Rf $(CARGOTMP);

rust_clean: $(SHLIB)
	rm -Rf $(CARGOTMP) $(VENDOR_DIR) @CLEAN_TARGET@

clean:
	rm -Rf $(SHLIB) $(STATLIB) $(OBJECTS) $(TARGET_DIR) $(VENDOR_DIR)
