#!/usr/bin/make -f

TRUECLOUDLAB_LINT_VERSION ?= 0.0.2
TMP_DIR := .cache
OUTPUT_LINT_DIR ?= $(shell pwd)/bin
LINT_VERSION ?= 1.55.1
LINT_DIR = $(OUTPUT_LINT_DIR)/golangci-lint-$(LINT_VERSION)-v$(TRUECLOUDLAB_LINT_VERSION)
EASYJSON_VERSION ?= $(shell go list -f '{{.Version}}' -m github.com/mailru/easyjson)
EASYJSON_DIR ?= $(shell pwd)/bin/easyjson-$(EASYJSON_VERSION)

# Run all code formatters
fmts: fmt imports

# Reformat code
fmt:
	@echo "⇒ Processing gofmt check"
	@gofumpt -s -w .

# Reformat imports
imports:
	@echo "⇒ Processing goimports check"
	@goimports -w .

# Run Unit Test with go test
test:
	@echo "⇒ Running go test"
	@go test ./... -count=1

# Activate pre-commit hooks
pre-commit:
	pre-commit install -t pre-commit -t commit-msg

# Deactivate pre-commit hooks
unpre-commit:
	pre-commit uninstall -t pre-commit -t commit-msg

pre-commit-run:
	@pre-commit run -a --hook-stage manual

# Install linters
lint-install:
	@mkdir -p $(TMP_DIR)
	@rm -rf $(TMP_DIR)/linters
	@git -c advice.detachedHead=false clone --branch v$(TRUECLOUDLAB_LINT_VERSION) https://git.frostfs.info/TrueCloudLab/linters.git $(TMP_DIR)/linters
	@make -C $(TMP_DIR)/linters lib CGO_ENABLED=1 OUT_DIR=$(OUTPUT_LINT_DIR)
	@rm -rf $(TMP_DIR)/linters
	@rmdir $(TMP_DIR) 2>/dev/null || true
	@CGO_ENABLED=1 GOBIN=$(LINT_DIR) go install github.com/golangci/golangci-lint/cmd/golangci-lint@v$(LINT_VERSION)

# Run linters
lint:
	@if [ ! -d "$(LINT_DIR)" ]; then \
		echo "Run make lint-install"; \
		exit 1; \
	fi
	@$(LINT_DIR)/golangci-lint run

# Install staticcheck
staticcheck-install:
	@go install honnef.co/go/tools/cmd/staticcheck@latest

# Run staticcheck
staticcheck-run:
	@staticcheck ./...

easyjson-install:
	@rm -rf $(EASYJSON_DIR)
	@mkdir -p $(EASYJSON_DIR)
	@GOBIN=$(EASYJSON_DIR) go install github.com/mailru/easyjson/...@$(EASYJSON_VERSION)

generate:
	@if [ ! -d "$(EASYJSON_DIR)" ]; then \
		make easyjson-install; \
	fi
	find ./ -name "_easyjson.go" -exec rm -rf {} \;
	$(EASYJSON_DIR)/easyjson ./pkg/chain/chain.go