.PHONY: build test lint fmt generate docker-operator clean tidy envtest patch minor major

BINARY_OP := bin/autobackup-operator
VERSION   ?= $(shell git describe --tags --always --dirty 2>/dev/null || echo "0.0.0-dev")

ENVTEST_K8S_VERSION ?= 1.31.0

build: tidy
	go build -ldflags="-s -w" -o $(BINARY_OP) ./cmd/operator

## envtest: fetch the envtest control-plane binaries and print KUBEBUILDER_ASSETS.
envtest:
	go run sigs.k8s.io/controller-runtime/tools/setup-envtest@latest use $(ENVTEST_K8S_VERSION) -p path

## test: run unit + envtest controller tests. The controller tests skip
## gracefully when the envtest binaries cannot be fetched.
test:
	KUBEBUILDER_ASSETS="$$(go run sigs.k8s.io/controller-runtime/tools/setup-envtest@latest use $(ENVTEST_K8S_VERSION) -p path 2>/dev/null)" \
		go test -race -count=1 -mod=vendor ./...

lint:
	go vet -mod=vendor ./...

fmt:
	gofmt -w .

## generate: regenerate the RBAC ClusterRole from kubebuilder markers.
generate:
	go run sigs.k8s.io/controller-tools/cmd/controller-gen@latest rbac:roleName=autobackup-operator \
		paths="./internal/controller/..." output:rbac:dir=config/rbac

docker-operator:
	docker build -t autobackup-operator:$(VERSION) -f Dockerfile.operator .

clean:
	rm -rf bin/

tidy:
	go mod tidy

_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" && git push origin $$NEW

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

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