TARGET_DIR = ./rust/target
LIBDIR = $(TARGET_DIR)/release
STATLIB = $(LIBDIR)/libtinyimg.a
PKG_LIBS = -L$(LIBDIR) -ltinyimg
PKG_CFLAGS = -pthread $(C_VISIBILITY)

all: $(SHLIB) cleanup

$(SHLIB): $(STATLIB)

CARGOTMP = $(CURDIR)/.cargo

$(STATLIB):
	# Report rustc version for R CMD check (per CRAN policy)
	@echo "Using Rust compiler:"
	@rustc --version || echo "rustc not found in PATH"
	# Extract vendored dependencies if present (for CRAN releases)
	@if [ -f ./rust/vendor.tar.xz ]; then \
		echo "Extracting vendored dependencies..."; \
		cd ./rust && tar xf vendor.tar.xz; \
	fi
	# Configure cargo to use vendored sources if vendor/ directory exists
	# The config must be in CARGO_HOME (which we set to $(CARGOTMP) = $(CURDIR)/.cargo)
	@if [ -d ./rust/vendor ]; then \
		echo "Configuring cargo to use vendored sources..."; \
		mkdir -p $(CARGOTMP); \
		echo '[source.crates-io]' > $(CARGOTMP)/config.toml; \
		echo 'replace-with = "vendored-sources"' >> $(CARGOTMP)/config.toml; \
		echo '' >> $(CARGOTMP)/config.toml; \
		echo '[source.vendored-sources]' >> $(CARGOTMP)/config.toml; \
		echo 'directory = "rust/vendor"' >> $(CARGOTMP)/config.toml; \
	fi
	# In some environments, ~/.cargo/bin might not be included in PATH, so we need
	# to set it here to ensure that cargo will be found. `rustc --print sysroot`
	# is a way to get the Rust sysroot without needing cargo itself.
	# Limit to 2 jobs per CRAN policy (cargo build -j defaults to number of logical CPUs)
	export CARGO_HOME=$(CARGOTMP) && \
		export PATH="$(PATH):$(HOME)/.cargo/bin" && \
		cargo build --lib --release --jobs 2 --manifest-path=./rust/Cargo.toml --target-dir $(TARGET_DIR)
	rm -Rf $(CARGOTMP) && \
		rm -Rf $(LIBDIR)/build && \
		rm -Rf ./rust/vendor

cleanup: $(SHLIB)
	rm -Rf $(STATLIB) $(TARGET_DIR)

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