GO ?= go
SHELL := /usr/bin/env bash

GOLANGCI_LINT_PACKAGE ?= github.com/golangci/golangci-lint/v2/cmd/golangci-lint@v2.12.2 # renovate: datasource=go

.PHONY: all
all: build

.PHONY: help
help:
	@echo "Available targets:"
	@echo " - build          build all packages"
	@echo " - test           run the tests"
	@echo " - vet            run go vet"
	@echo " - lint           run golangci-lint"
	@echo " - fmt            format the code"
	@echo " - fmt-check      check that the code is formatted"
	@echo " - tidy           run go mod tidy"
	@echo " - tidy-check     check that go.mod/go.sum are tidy"
	@echo " - checks         run all checks (fmt-check, tidy-check, vet, lint)"

.PHONY: build
build:
	$(GO) build ./...

.PHONY: test
test:
	$(GO) test $(GOTESTFLAGS) ./...

.PHONY: vet
vet:
	$(GO) vet ./...

.PHONY: lint
lint:
	$(GO) run $(GOLANGCI_LINT_PACKAGE) run

.PHONY: fmt
fmt:
	$(GO) run $(GOLANGCI_LINT_PACKAGE) fmt

.PHONY: fmt-check
fmt-check:
	@files="$$($(GO) run $(GOLANGCI_LINT_PACKAGE) fmt --diff)"; \
	if [ -n "$$files" ]; then \
		echo "The following files are not formatted, run 'make fmt':"; \
		echo "$$files"; \
		exit 1; \
	fi

.PHONY: tidy
tidy:
	$(GO) mod tidy

.PHONY: tidy-check
tidy-check:
	@cp go.mod go.mod.bak && cp go.sum go.sum.bak; \
	$(MAKE) --no-print-directory tidy; \
	code=0; \
	diff -u go.mod.bak go.mod || code=1; \
	diff -u go.sum.bak go.sum || code=1; \
	mv go.mod.bak go.mod && mv go.sum.bak go.sum; \
	if [ $$code -ne 0 ]; then echo "go.mod/go.sum are not tidy, run 'make tidy'"; fi; \
	exit $$code

.PHONY: checks
checks: fmt-check tidy-check vet lint
