SDK_MODULE := git.dev.alexdunmow.com/block/core
SDK_VERSION ?= $(shell git describe --tags --abbrev=0)

SDK_DOWNSTREAM_DIRS := \
	$(HOME)/src/blockninja/backend \
	$(HOME)/src/orchestrator/backend \
	$(wildcard $(HOME)/src/blockninja-themes/*) \
	$(HOME)/src/assumechaos \
	$(HOME)/src/bidbuddy \
	$(HOME)/src/bidmasters \
	$(HOME)/src/coterieos \
	$(HOME)/src/messenger \
	$(HOME)/src/perthplaygrounds \
	$(HOME)/src/symposium

.PHONY: install-ninja
install-ninja:
	go install ./cmd/ninja

.PHONY: update-sdk
update-sdk:
	@set -e; \
	for dir in $(SDK_DOWNSTREAM_DIRS); do \
		if [ ! -f "$$dir/go.mod" ]; then \
			echo "skip $$dir (no go.mod)"; \
			continue; \
		fi; \
		echo "==> $$dir: $(SDK_MODULE)@$(SDK_VERSION)"; \
		( \
			cd "$$dir"; \
			go mod edit -dropreplace=$(SDK_MODULE) 2>/dev/null || true; \
			go get $(SDK_MODULE)@$(SDK_VERSION); \
			go mod tidy; \
			if grep -q '^replace $(SDK_MODULE)' go.mod; then \
				echo "replace directive still present in $$dir/go.mod" >&2; \
				exit 1; \
			fi; \
		); \
	done

# Tag + push a new SDK release, then bump the pin in every downstream repo.
# Usage: make release VERSION=v0.11.0
.PHONY: release
release:
	@if [ -z "$(VERSION)" ]; then echo "usage: make release VERSION=vX.Y.Z" >&2; exit 1; fi
	@case "$(VERSION)" in v[0-9]*.[0-9]*.[0-9]*) ;; *) echo "VERSION must look like vX.Y.Z (got $(VERSION))" >&2; exit 1 ;; esac
	@if ! git diff-index --quiet HEAD --; then echo "working tree dirty; commit before releasing" >&2; exit 1; fi
	git push origin HEAD
	git tag -a "$(VERSION)" -m "release $(VERSION)"
	git push origin "$(VERSION)"
	$(MAKE) update-sdk SDK_VERSION=$(VERSION)
	@echo "==> $(VERSION) tagged + pushed; downstream go.mod files bumped."
	@echo "    Review each downstream and commit the pin bump."

.PHONY: check-sdk-pins
check-sdk-pins:
	@set -e; \
	for dir in $(SDK_DOWNSTREAM_DIRS); do \
		if [ ! -f "$$dir/go.mod" ]; then \
			continue; \
		fi; \
		if grep -q '^replace $(SDK_MODULE)' "$$dir/go.mod"; then \
			echo "replace directive found in $$dir/go.mod" >&2; \
			exit 1; \
		fi; \
		if ! grep -Eq '^[[:space:]]*(require[[:space:]]+)?$(SDK_MODULE)[[:space:]]+v[0-9]+\.[0-9]+\.[0-9]+' "$$dir/go.mod"; then \
			echo "$(SDK_MODULE) is not pinned in $$dir/go.mod" >&2; \
			exit 1; \
		fi; \
	done
