# benvin-utils — a collection of small tools. Each tool is a directory
# containing a `package main`; the shared library lives under common/.
#
# Tools are auto-discovered, so adding a new tool directory needs no Makefile
# edits: `make all`, `make install`, and `make <tool>` just pick it up.

GO      ?= go
BINDIR  ?= bin
# GOBIN, else $(go env GOPATH)/bin — where `make install` puts binaries.
GOBIN   ?= $(shell $(GO) env GOBIN)
ifeq ($(GOBIN),)
GOBIN   := $(shell $(GO) env GOPATH)/bin
endif

# A directory is a "tool" if it holds at least one *.go file with `package main`
# and is not the shared library or hidden/dot dir.
TOOLS := $(sort $(patsubst %/,%,$(dir $(shell grep -rl --include='*.go' '^package main' . 2>/dev/null))))
TOOLS := $(filter-out ./common%,$(TOOLS))
TOOLS := $(patsubst ./%,%,$(TOOLS))

.DEFAULT_GOAL := all

.PHONY: all
all: $(TOOLS) ## Build every tool into ./bin

# Pattern rule: `make <tool>` builds that one tool into ./bin/<tool>.
.PHONY: $(TOOLS)
$(TOOLS): %: | $(BINDIR)
	@echo "  build  $@"
	@$(GO) build -o $(BINDIR)/$@ ./$@

$(BINDIR):
	@mkdir -p $(BINDIR)

.PHONY: install
install: ## Install every tool into $(GOBIN)
	@echo "  install → $(GOBIN)"
	@$(GO) install ./...

.PHONY: test
test: ## Run all tests
	@$(GO) test ./...

.PHONY: tidy
tidy: ## go mod tidy
	@$(GO) mod tidy

.PHONY: fmt vet
fmt: ; @$(GO) fmt ./...
vet: ; @$(GO) vet ./...

.PHONY: clean
clean: ## Remove built binaries
	@rm -rf $(BINDIR)

.PHONY: list
list: ## List discovered tools
	@echo $(TOOLS)

.PHONY: help
help: ## Show this help
	@echo "benvin-utils — tools: $(TOOLS)"
	@echo
	@grep -hE '^[a-zA-Z_$$()%-]+:.*?## ' $(MAKEFILE_LIST) | \
		sort | awk 'BEGIN{FS=":.*?## "}{printf "  \033[36m%-12s\033[0m %s\n", $$1, $$2}'
	@echo
	@echo "  make <tool>   Build one tool (e.g. make podgap)"
