# SPDX-License-Identifier: GPL-3.0-or-later
# Works with GNU make and BSD make.

DESTDIR ?=
PREFIX  ?= $(HOME)/.local
BINDIR   = $(DESTDIR)$(PREFIX)/bin
BIN      = krino
VERSION != git describe --tags --always --dirty 2>/dev/null || echo dev
LDFLAGS  = -s -w -X main.version=$(VERSION)

.PHONY: all help build install uninstall test vet fmt ci install-hooks clean

all: build

help: ## show this help
	@grep -E '^[a-z-]+:.*## ' Makefile | \
	  awk 'BEGIN {FS = ":.*## "}; {printf "  %-10s %s\n", $$1, $$2}'
	@echo "  version: $(VERSION)   prefix: $(PREFIX)"

build: ## build ./krino; Go fetches module dependencies itself
	CGO_ENABLED=0 go build -trimpath -ldflags "$(LDFLAGS)" -o $(BIN) ./cmd/krino

install: build ## install to $(PREFIX)/bin
	mkdir -p $(BINDIR)
	rm -f $(BINDIR)/$(BIN)
	install -m 755 $(BIN) $(BINDIR)/$(BIN)

uninstall: ## remove the installed binary
	rm -f $(BINDIR)/$(BIN)

test: ## run the tests
	go test ./...

vet: ## go vet
	go vet ./...

fmt: ## gofmt the tree
	gofmt -w .

ci: ## the gate: gofmt, vet, tests, dependencies, no personal data staged
	@test -z "$$(gofmt -l .)" || { echo "gofmt needed:"; gofmt -l .; exit 1; }
	go vet ./...
	GOOS=freebsd CGO_ENABLED=0 go vet ./...
	GOOS=openbsd CGO_ENABLED=0 go vet ./...
	go test ./...
	@deps=$$(go list -deps ./... | grep -E '^[a-z0-9-]+\.[a-z]+/' | grep -vE '^golang\.org/x/(term|text|sys)(/|$$)' || true); \
	  test -z "$$deps" || { echo "unexpected dependencies:"; echo "$$deps"; exit 1; }
	@scripts/leak-check
	@echo "ci ok"

install-hooks: ## install the pre-commit hook that runs the leak check
	install -m 755 scripts/hooks/pre-commit "$$(git rev-parse --git-path hooks)/pre-commit"

clean: ## remove build output
	rm -f $(BIN)
