VENDORING = yes
TARGET_DIR = ./rust/target
LIBDIR = $(TARGET_DIR)/release
STATLIB = $(LIBDIR)/libtok.a
PKG_LIBS = -L$(LIBDIR) -ltok
CARGOTMP = $(CURDIR)/.cargo

all: C_clean
$(SHLIB): $(STATLIB)

$(STATLIB):
	# In some environments, ~/.cargo/bin might not be included in PATH, so we need
	# to set it here to ensure cargo can be invoked. It is appended to PATH and
	# therefore is only used if cargo is absent from the user's PATH.

	@echo "*** Rust version: $$(rustc --version)"
	
	if [ "$(VENDORING)" = "yes" ]; then \
		$(TAR) --extract --xz -f ./rust/vendor.tar.xz -C ./rust && \
	    mkdir -p ./rust/.cargo; \
	fi
	
	export PATH="$(PATH):$(HOME)/.cargo/bin" && \
		if [ "$(NOT_CRAN)" != "true" ]; then \
 			export CARGO_HOME=$(CARGOTMP); \
		fi && \
		cargo build --lib --release --offline --config rust/config/cargo-config.toml --manifest-path=./rust/Cargo.toml --target-dir $(TARGET_DIR) --jobs 1

	# we clean headers to avoid a message like
	# Found the following sources/headers with CR or CRLF line endings:
    # src/rust/vendor/clang-sys/tests/header.h
	@echo "*** Cleaning headers"
	"${R_HOME}/bin${R_ARCH_BIN}/Rscript" "../tools/patch.R"
		
	if [ "$(NOT_CRAN)" != "true" ]; then \
		rm -Rf $(CARGOTMP) && \
		rm -Rf $(LIBDIR)/build; \
	fi
		
C_clean:
	rm -Rf $(SHLIB) $(STATLIB) $(OBJECTS)

clean:
	rm -Rf $(SHLIB) $(STATLIB) $(OBJECTS) rust/target
	
