BASE_REF ?= main
HEAD_REF ?= HEAD

define clone-repo
	mkdir -p $(1)
	git -C $(1) init
	git -C $(1) remote add origin $(2) || true
	git -C $(1) fetch origin $(3)
	git -C $(1) -c advice.detachedHead=false checkout $(3)
	test `git -C $(1) rev-parse HEAD` = $(3)
endef

docs/book: docs/src/links.md $(shell find docs/src -type f -name '*.md')
	mdbook build docs
	mkdir -p docs/book/rustdoc
	cargo doc --no-deps
	cp -r ${CARGO_TARGET_DIR}/doc/* docs/book/rustdoc/

docs/src/links.md: docs/src/links.md.template
	echo "<!-- DO NOT EDIT THIS FILE MANUALLY, edit links.md.template -->" > $@
	envsubst < $< >> $@

.PHONY: touch
touch:
	touch docs/src/links.md.template

.PHONY: review
review:
	$(eval BASE_REF_PARSED := $(shell git rev-parse $(BASE_REF)))
	$(eval HEAD_REF_PARSED := $(shell git rev-parse $(HEAD_REF)))
	@echo "Ensuring current HEAD_REF is not BASE_REF"
	test "$(BASE_REF_PARSED)" != "$(HEAD_REF_PARSED)"
	@echo "Verifying if any changes happened in Cargo.lock that require review; otherwise, use `git difftool` directly"
	test "$(shell git show $(BASE_REF_PARSED):Cargo.lock | sha256sum)" != "$(shell git show $(HEAD_REF_PARSED):Cargo.lock | sha256sum)"
	$(eval TEMP_REPO := $(shell mktemp -d))
	$(call clone-repo,$(TEMP_REPO),$(shell dirname $(realpath $(firstword $(MAKEFILE_LIST)))),$(BASE_REF_PARSED))
	# Unstage current commit before refreeze
	git -C $(TEMP_REPO) reset --hard 'HEAD^1'
	# Fetch files for BASE_REF
	cd $(TEMP_REPO) && CARGO_HOME=$(TEMP_REPO)/cargo-home cargo fetch
	echo "cargo-home/registry/cache" >> $(TEMP_REPO)/.gitignore
	echo "cargo-home/registry/index" >> $(TEMP_REPO)/.gitignore
	echo "cargo-home/registry/CACHEDIR.TAG" >> $(TEMP_REPO)/.gitignore
	git -C $(TEMP_REPO) add .
	git -C $(TEMP_REPO) commit --no-gpg-sign -m "base ref: $(BASE_REF)"
	# git -C $(TEMP_REPO) ls-files -z | (cd $(TEMP_REPO); xargs -0 -n1 rm)
	git -C $(TEMP_REPO) fetch origin $(HEAD_REF_PARSED)
	git -C $(TEMP_REPO) merge --no-commit $(HEAD_REF_PARSED)
	rm -rf $(TEMP_REPO)/cargo-home/registry/src
	# Fetch files for HEAD_REF
	cd $(TEMP_REPO) && CARGO_HOME=$(TEMP_REPO)/cargo-home cargo fetch
	git -C $(TEMP_REPO) add -A .
	git -C $(TEMP_REPO) difftool --diff-filter=r HEAD || true
	# rm -rf $(TEMP_REPO)