TARGET_DIR = ./rust/target
LIBDIR = $(TARGET_DIR)/release
STATLIB = $(LIBDIR)/libchuron.a
PKG_LIBS = -L$(LIBDIR) -lchuron

# Load ONNX Runtime configuration if available
-include ort_config.env

all: C_clean

$(SHLIB): $(STATLIB)

CARGOTMP = $(CURDIR)/.cargo

# Vendor config flags (set if vendor exists)
VENDOR_FLAGS = 

$(STATLIB):
	# Check rustc version
	rustc --version
	
	# Vendor setup: extract vendored crates and configure cargo
	if [ -f ./rust/vendor.tar.xz ]; then \
		tar -xf ./rust/vendor.tar.xz -C $(CURDIR) && \
		mkdir -p $(CARGOTMP) && \
		cp ./rust/vendor-config.toml $(CARGOTMP)/config.toml; \
	fi
	
	# Load ONNX Runtime environment variables
	if [ -f "ort_config.env" ]; then \
		. ./ort_config.env; \
	fi; \
	# 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.
	if [ "$(NOT_CRAN)" != "true" ]; then \
		export CARGO_HOME=$(CARGOTMP); \
	fi && \
		export PATH="$(PATH):$(HOME)/.cargo/bin" && \
		if [ -f "ort_config.env" ]; then . ./ort_config.env; fi && \
		if [ -f ./rust/vendor.tar.xz ]; then \
			cargo build --jobs 2 --lib --release --offline --manifest-path=./rust/Cargo.toml --target-dir $(TARGET_DIR); \
		else \
			cargo build --jobs 2 --lib --release --manifest-path=./rust/Cargo.toml --target-dir $(TARGET_DIR); \
		fi
	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
