TARGET_DIR = $(CURDIR)/rust/target
LIBDIR = $(TARGET_DIR)/release
STATLIB = $(LIBDIR)/libpdfrune_r.a
PKG_CFLAGS = -pthread $(C_VISIBILITY)
PKG_LIBS = -L$(LIBDIR) -lpdfrune_r -lpthread -ldl -lm

all: $(SHLIB) cleanup

$(SHLIB): $(STATLIB)

# CRAN policy forbids writing to $HOME and restricts builds to at most 2 CPUs
CARGOTMP = $(CURDIR)/.cargo
export CARGO_HOME = $(CARGOTMP)
CRANFLAGS = -j 2

$(STATLIB):
	@echo "Checking Rust toolchain version prior to compilation..."
	@PATH="${PATH}:${HOME}/.cargo/bin" cargo --version
	@PATH="${PATH}:${HOME}/.cargo/bin" rustc --version
	@mkdir -p $(TARGET_DIR)
	if [ -f rust/vendor.tar.xz ]; then \
		tar xf rust/vendor.tar.xz && \
		mkdir -p $(CARGOTMP) && \
		cp rust/vendor-config.toml $(CARGOTMP)/config.toml; \
	fi
	PATH="${PATH}:${HOME}/.cargo/bin" cargo build ${CRANFLAGS} --offline --release --manifest-path rust/Cargo.toml --target-dir $(TARGET_DIR)
	@rm -Rf $(CARGOTMP) vendor || true
	@rm -Rf $(LIBDIR)/build || true

cleanup: $(SHLIB)
	@rm -Rf $(STATLIB) $(TARGET_DIR) vendor $(CARGOTMP) || true

clean:
	@rm -Rf $(SHLIB) $(OBJECTS) $(STATLIB) $(TARGET_DIR) vendor $(CARGOTMP) symbols.rds || true
