BINARY   := go-cache-plugin
# Upstream has no releases; the shipped binary is built from the module version
# pinned by the tool directive in go.mod.
PKG      := github.com/tailscale/go-cache-plugin/cmd/go-cache-plugin
DIST     := dist
IMAGE    := artifactapi.k8s.syd1.au.unkin.net/docker-internal/$(BINARY)
VERSION  := $(shell git describe --tags --always --dirty 2>/dev/null || echo dev)
UPSTREAM := $(shell go list -m -f '{{.Version}}' github.com/tailscale/go-cache-plugin)
LDFLAGS  := -s -w
OS       ?= $(shell go env GOOS)
ARCH     ?= $(shell go env GOARCH)

.PHONY: all build test lint fmt pre-commit docker clean upstream patch minor major _tag

all: build

# Static so the released binary runs on any image in the estate, Alpine included.
build:
	CGO_ENABLED=0 GOOS=$(OS) GOARCH=$(ARCH) go build -ldflags="$(LDFLAGS)" -o $(DIST)/$(BINARY) $(PKG)

# -count=1: the tests build via `make build`, and the Makefile is not a go test
# cache input, so a cached PASS would outlive a broken build recipe.
test:
	go test -race -count=1 -v ./...

lint:
	golangci-lint run ./...

fmt:
	gofmt -w .

pre-commit:
	uvx pre-commit run --all-files

# Local smoke test only; the tag pipeline builds and pushes the real image.
docker:
	docker build -t $(IMAGE):$(VERSION) .

upstream:
	@echo $(UPSTREAM)

clean:
	rm -rf $(DIST)

# Bump helpers -- reads the latest semver tag and creates the next one.
# If no tag exists yet, starts from v0.0.0.
_LATEST := $(shell git tag --sort=-v:refname | grep -E '^v[0-9]+\.[0-9]+\.[0-9]+$$' | head -1)
_BASE   := $(if $(_LATEST),$(_LATEST),v0.0.0)
_MAJ    := $(shell echo $(_BASE) | sed 's/^v//' | cut -d. -f1)
_MIN    := $(shell echo $(_BASE) | sed 's/^v//' | cut -d. -f2)
_PAT    := $(shell echo $(_BASE) | sed 's/^v//' | cut -d. -f3)

patch:
	@NEW=v$(_MAJ).$(_MIN).$(shell expr $(_PAT) + 1); \
	git tag $$NEW && echo "Tagged $$NEW" && $(MAKE) _tag TAG=$$NEW

minor:
	@NEW=v$(_MAJ).$(shell expr $(_MIN) + 1).0; \
	git tag $$NEW && echo "Tagged $$NEW" && $(MAKE) _tag TAG=$$NEW

major:
	@NEW=v$(shell expr $(_MAJ) + 1).0.0; \
	git tag $$NEW && echo "Tagged $$NEW" && $(MAKE) _tag TAG=$$NEW

_tag:
	git push origin $(TAG)
