# All shipped binaries, discovered from cmd/. Every tool is a separate main
# package there, so adding one needs no edit here.
BINARIES := $(notdir $(wildcard cmd/*))
DIST    := dist
BINDIR  := $(DIST)/bin
COMPDIR := $(DIST)/completions
VERSION := $(shell git describe --tags --always --dirty 2>/dev/null || echo dev)
GOFLAGS := -ldflags="-s -w -X main.version=$(VERSION)"
OS      ?= $(shell go env GOOS)
ARCH    ?= $(shell go env GOARCH)

.PHONY: all build test lint fmt pre-commit clean install completions print-binaries rpm rpm-package patch minor major _tag

all: build

# Build every binary into dist/bin so the nfpm packaging step
# (scripts/build-rpm.sh) can find them. Each main package needs its own -o, so
# they are built individually rather than with a single ./... invocation.
build:
	@for b in $(BINARIES); do \
		echo "building $$b"; \
		CGO_ENABLED=0 GOOS=$(OS) GOARCH=$(ARCH) go build $(GOFLAGS) -o $(BINDIR)/$$b ./cmd/$$b || exit 1; \
	done

# The binary list, for CI steps that cross-compile the same set.
print-binaries:
	@echo $(BINARIES)

test:
	go test -v -race ./...

lint:
	golangci-lint run ./...

fmt:
	gofmt -w .

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

clean:
	rm -rf $(DIST)

install:
	go install $(GOFLAGS) ./...

# Generate bash/zsh/fish completions for every binary into dist/completions,
# named and laid out exactly as they install (the RPM globs these directories).
completions: build
	@mkdir -p $(COMPDIR)/bash $(COMPDIR)/zsh $(COMPDIR)/fish
	@for b in $(BINARIES); do \
		$(BINDIR)/$$b completion bash > $(COMPDIR)/bash/$$b; \
		$(BINDIR)/$$b completion zsh  > $(COMPDIR)/zsh/_$$b; \
		$(BINDIR)/$$b completion fish > $(COMPDIR)/fish/$$b.fish; \
	done

# Build the binaries then package them (with completions) into an RPM via nfpm.
rpm: build rpm-package

# Package already-built binaries into an RPM (used by CI after the build step).
rpm-package:
	./scripts/build-rpm.sh $(VERSION)

# Bump helpers — read the latest semver tag and create the next one.
# If no tag exists yet, start 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)
