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:"
	@PATH="$(PATH):$(HOME)/.cargo/bin" 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" && \
		if [ "$$(uname -s)" = "Darwin" ] && [ -z "$$MACOSX_DEPLOYMENT_TARGET" ]; then \
			R_FLAGS="$$(R CMD config CC 2>/dev/null) $$(R CMD config CFLAGS 2>/dev/null) $$(R CMD config LDFLAGS 2>/dev/null)"; \
			DEPLOY_TARGET="$$(echo "$$R_FLAGS" | sed -n 's/.*-version-min=\([0-9][0-9.]*\).*/\1/p' | head -n 1)"; \
			if [ -z "$$DEPLOY_TARGET" ]; then \
				DARWIN_VER="$$(R --version | sed -n 's/.*-apple-darwin\([0-9]*\).*/\1/p')"; \
				if [ -n "$$DARWIN_VER" ]; then \
					DEPLOY_TARGET=$$((DARWIN_VER - 9)); \
				fi; \
			fi; \
			if [ -n "$$DEPLOY_TARGET" ]; then \
			    if [ -z "$$CI" ] || [ "$$DEPLOY_TARGET" != "11" ]; then \
			    	export MACOSX_DEPLOYMENT_TARGET="$$DEPLOY_TARGET"; \
			    fi; \
			fi; \
		fi && \
		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
