# Terminal — build helpers (.so plugin workflow)
#
# The plugin compiles to a .so shared object loaded by the CMS at runtime.
#
# Usage:
#   make          # Default: build terminal.so locally
#   make clean    # Remove built artefacts
#   make templ    # Regenerate *_templ.go

.PHONY: all clean templ help bump-patch bump-minor bump-major sync-version

PLUGIN_NAME := terminal
TEMPL       := $(HOME)/go/bin/templ

# Default target: build the .so locally
all: $(PLUGIN_NAME).so

# Local plugin build
$(PLUGIN_NAME).so: $(wildcard *.go) plugin.mod go.mod
	CGO_ENABLED=1 go build -buildmode=plugin -ldflags="-s -w" -o $(PLUGIN_NAME).so .

# Regenerate templ Go files
templ:
	$(TEMPL) generate

clean:
	rm -f $(PLUGIN_NAME).so

help:
	@echo "Targets:"
	@echo "  all     Build $(PLUGIN_NAME).so locally (default)"
	@echo "  templ   Regenerate templ Go files"
	@echo "  clean   Remove built artefacts"

# --- Version bump targets ---
CURRENT_VERSION := $(shell grep '^version' plugin.mod | sed 's/.*"\(.*\)"/\1/')

bump-patch:
	@NEW=$$(echo $(CURRENT_VERSION) | awk -F. '{printf "%d.%d.%d", $$1, $$2, $$3+1}'); \
	sed -i 's/version = "$(CURRENT_VERSION)"/version = "'$$NEW'"/' plugin.mod; \
	git add plugin.mod && git commit -m "chore: bump version to $$NEW" && git tag "v$$NEW"; \
	echo "Bumped to $$NEW and tagged v$$NEW"

bump-minor:
	@NEW=$$(echo $(CURRENT_VERSION) | awk -F. '{printf "%d.%d.0", $$1, $$2+1}'); \
	sed -i 's/version = "$(CURRENT_VERSION)"/version = "'$$NEW'"/' plugin.mod; \
	git add plugin.mod && git commit -m "chore: bump version to $$NEW" && git tag "v$$NEW"; \
	echo "Bumped to $$NEW and tagged v$$NEW"

bump-major:
	@NEW=$$(echo $(CURRENT_VERSION) | awk -F. '{printf "%d.0.0", $$1+1}'); \
	sed -i 's/version = "$(CURRENT_VERSION)"/version = "'$$NEW'"/' plugin.mod; \
	git add plugin.mod && git commit -m "chore: bump version to $$NEW" && git tag "v$$NEW"; \
	echo "Bumped to $$NEW and tagged v$$NEW"

sync-version:
	@TAG=$$(git describe --tags --abbrev=0 2>/dev/null | sed 's/^v//'); \
	if [ -z "$$TAG" ]; then echo "No tags found"; exit 1; fi; \
	sed -i 's/version = "$(CURRENT_VERSION)"/version = "'$$TAG'"/' plugin.mod; \
	echo "Synced plugin.mod to $$TAG"
