BINARY     := unitdore
INSTALL_DIR := /usr/bin
CONFIG_DIR  := /etc/unitdore
VERSION    := $(shell git describe --tags --always --dirty 2>/dev/null || echo "dev")
LDFLAGS    := -ldflags "-X github.com/warkanum/unitdore/cmd.version=$(VERSION)"

.PHONY: all build install uninstall test lint clean release-version pkg-checksums

all: build

## build: compile the binary
build:
	go build $(LDFLAGS) -o $(BINARY) .

## install: install binary, man page, and create config dir
install: build
	install -Dm755 $(BINARY) $(INSTALL_DIR)/$(BINARY)
	install -Dm644 docs/unitdore.1 /usr/share/man/man1/unitdore.1
	mkdir -p $(CONFIG_DIR)
	@echo "Installed to $(INSTALL_DIR)/$(BINARY)"
	@echo "Config dir: $(CONFIG_DIR)"

## uninstall: remove binary and man page
uninstall:
	rm -f $(INSTALL_DIR)/$(BINARY)
	rm -f /usr/share/man/man1/unitdore.1
	@echo "Removed $(INSTALL_DIR)/$(BINARY)"

## test: run all unit tests
test:
	go test ./... -v

## test-short: run tests without verbose output
test-short:
	go test ./...

## lint: run go vet
lint:
	go vet ./...

## clean: remove built binary
clean:
	rm -f $(BINARY)

# VERSION only counts as a release version when given on the command line
# (it defaults to git describe for the build flags).
RELEASE_VERSION := $(if $(filter command line,$(origin VERSION)),$(patsubst v%,%,$(VERSION)))

## release-version: bump version (patch, or VERSION=X.Y.Z), update source and package versions, commit, tag, and push
release-version:
	@if [ -n "$(RELEASE_VERSION)" ]; then \
		echo "$(RELEASE_VERSION)" | grep -Eq '^[0-9]+\.[0-9]+\.[0-9]+$$' || { echo "usage: make release-version [VERSION=X.Y.Z]"; exit 1; }; \
		PKGVER="$(RELEASE_VERSION)"; \
	else \
		CURRENT=$$(git describe --tags --abbrev=0 2>/dev/null || echo "v0.0.0"); \
		MAJOR=$$(echo $$CURRENT | sed 's/v\([0-9]*\)\.\([0-9]*\)\.\([0-9]*\).*/\1/'); \
		MINOR=$$(echo $$CURRENT | sed 's/v\([0-9]*\)\.\([0-9]*\)\.\([0-9]*\).*/\2/'); \
		PATCH=$$(echo $$CURRENT | sed 's/v\([0-9]*\)\.\([0-9]*\)\.\([0-9]*\).*/\3/'); \
		PKGVER="$$MAJOR.$$MINOR.$$((PATCH + 1))"; \
	fi; \
	NEXT="v$$PKGVER"; \
	if git rev-parse -q --verify "refs/tags/$$NEXT" >/dev/null; then echo "tag $$NEXT already exists"; exit 1; fi; \
	echo "Releasing $$NEXT"; \
	scripts/bump-version.sh "$$PKGVER"; \
	git add -A cmd/root.go pkg; \
	git commit -m "chore(release): update package version to $$PKGVER"; \
	git tag -a "$$NEXT" -m "Release $$NEXT"; \
	git push origin HEAD "$$NEXT"; \
	echo "Pushed $$NEXT — release workflow triggered"

## pkg-checksums: fill the Void checksum from the published release (run after release)
pkg-checksums:
	scripts/update-checksums.sh

## help: show this help
help:
	@grep -E '^## ' Makefile | sed 's/## /  /'
