#!/usr/bin/make -f

ANTLR_VERSION="4.13.0"
TMP_DIR := .cache
LINT_VERSION ?= 1.55.0
TRUECLOUDLAB_LINT_VERSION ?= 0.0.2
OUTPUT_LINT_DIR ?= $(shell pwd)/bin
LINT_DIR = $(OUTPUT_LINT_DIR)/golangci-lint-$(LINT_VERSION)-v$(TRUECLOUDLAB_LINT_VERSION)

# Run tests
test:
	@go test ./... -cover -count=1

# Pull go dependencies
dep:
	@printf "⇒ Download requirements: "
	@CGO_ENABLED=0 \
	go mod download && echo OK
	@printf "⇒ Tidy requirements: "
	@CGO_ENABLED=0 \
	go mod tidy -v && echo OK

# 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

# Run tests with race detection and produce coverage output
cover:
	@go test -v -race ./... -coverprofile=coverage.txt -covermode=atomic
	@go tool cover -html=coverage.txt -o coverage.html

# Reformat code
format:
	@echo "⇒ Processing gofmt check"
	@gofmt -s -w ./
	@echo "⇒ Processing goimports check"
	@goimports -w ./

policy:
	@wget -q https://www.antlr.org/download/antlr-${ANTLR_VERSION}-complete.jar -O antlr4-tool.jar
	@java -Xmx500M -cp "`pwd`/antlr4-tool.jar" "org.antlr.v4.Tool" -o `pwd`/netmap/parser/ -Dlanguage=Go -no-listener -visitor `pwd`/netmap/parser/Query.g4 `pwd`/netmap/parser/QueryLexer.g4

# Run `make %` in truecloudlab/frostfs-sdk-go container(Golang+Java)
docker/%:
	@docker build -t truecloudlab/frostfs-sdk-go --platform linux/amd64 . > /dev/null
	@docker run --rm -t \
	-v `pwd`:/work \
	-u "$$(id -u):$$(id -g)" \
	--env HOME=/work \
	truecloudlab/frostfs-sdk-go make $*

# Synchronize tree service
sync-tree:
	@./syncTree.sh

# Show this help prompt
help:
	@echo '  Usage:'
	@echo ''
	@echo '    make <target>'
	@echo ''
	@echo '  Targets:'
	@echo ''
	@awk '/^#/{ comment = substr($$0,3) } comment && /^[a-zA-Z][a-zA-Z0-9_-]+ ?:/{ print "   ", $$1, comment }' $(MAKEFILE_LIST) | column -t -s ':' | grep -v 'IGNORE' | sort -u