IMG ?= cluster-agent:local
DOCKER_PLATFORMS ?= linux/amd64,linux/arm64
SKIP_BUILD ?= false

ARCH ?= $(shell go env GOARCH)

.PHONY: build dev docker-build build-linux test

check: build unit lint
	go mod tidy

dev: build unit

test: unit

### Build ###

build:
	CGO_ENABLED=0 go build -ldflags="-s -w" -o bin/cluster-agent cmd/agent/*

.PHONY: build-linux
build-linux:
	CGO_ENABLED=0 GOOS=linux GOARCH=$(ARCH) go build -ldflags="-s -w" -o bin/cluster-agent-linux cmd/agent/*

.PHONY: docker-build
docker-build: build-linux
	docker build -t ${IMG} -f Dockerfile ./

.PHONY: docker-push
docker-push:
	docker push $(IMG)

.PHONY: docker-safe-push
docker-safe-push:
	@echo "Checking if $(IMG) exists..."
	@if docker manifest inspect $(IMG) > /dev/null 2>&1; then \
		echo "Image $(IMG) already exists, skipping push"; \
	else \
		echo "Pushing $(IMG)..."; \
		docker push $(IMG); \
	fi

### CI ###

unit:
	go test -vet=all -short ./...

.PHONY: lint
lint: golangci-lint
	$(GOLANGCI_LINT) run ./...

.PHONY: lint-fix
lint-fix: golangci-lint ## Fix linting issues.
	$(GOLANGCI_LINT) run --fix ./...

GOLANGCI_LINT = $(shell pwd)/bin/golangci-lint
golangci-lint: ## Download golangci-lint locally if necessary
	$(call go-get-tool,$(GOLANGCI_LINT),github.com/golangci/golangci-lint/v2/cmd/golangci-lint@v2.10.1)

.PHONY: generate
generate:
	go generate ./...

### E2E ###

.PHONY: e2e-images
e2e-images: build-linux
	docker build -t cluster-agent:e2e -f Dockerfile ./

.PHONY: e2e-run
e2e-run:
	@which kind   >/dev/null 2>&1 || { echo "kind not found, install from https://kind.sigs.k8s.io/"; exit 1; }
	@which kubectl >/dev/null 2>&1 || { echo "kubectl not found"; exit 1; }
	@which e2e    >/dev/null 2>&1 || { echo "e2e not found, install skywalking-infra-e2e"; exit 1; }
	e2e run -c test/e2e/e2e.yaml

### Common tools ###

# go-get-tool will 'go get' any package $2 and install it to $1.
PROJECT_DIR := $(shell dirname $(abspath $(lastword $(MAKEFILE_LIST))))
define go-get-tool
@[ -f $(1) ] || { \
set -e ;\
TMP_DIR=$$(mktemp -d) ;\
cd $$TMP_DIR ;\
go mod init tmp ;\
echo "Downloading $(2)" ;\
GOBIN=$(PROJECT_DIR)/bin go install $(2) ;\
rm -rf $$TMP_DIR ;\
}
endef
