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

ifeq ($(shell uname -m),aarch64)
	ARCH=arm64
else
	ARCH=amd64
endif

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

check: build test
	go mod tidy

dev: build test

### Build ###

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

.PHONY: local-build-image build-linux local-push-image local-build-and-push local-run
local-build-image: build-linux
	docker build -f ./local/Dockerfile_local . -t ${IMG}

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

local-push-image: ## Push the config-manager docker image.
	docker push ${IMG}

local-build-and-push:
	./local/local-build.sh

# Run cluster-agent on your laptop
local-run:
	./local/local-run.sh

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

# Run cluster-agent on your laptop within docker
docker-run:
	DOCKER_PLATFORMS=linux/$(ARCH) make local-build-image
	docker run -e TIKV_CTL_PATH=/bin/echo -e PD_CTL_PATH=/bin/echo -e PD_PATROL_CTL_PATH=/bin/echo -it --rm -p8080:8080 --name cluster-agent cluster-agent:local

### Run cluster-agent in KinD ###

# install e2e-cli
e2e-cli:
	@if ! command -v e2e &> /dev/null; then \
		go install github.com/apache/skywalking-infra-e2e/cmd/e2e@v1.3.0; \
	fi

# Pull images for KinD cluster
prepare-images:
	docker pull pingcap/pd:v7.5.1
	docker pull pingcap/tikv:v7.5.1
	docker pull pingcap/tidb:v7.5.1

# Create a KinD cluster and deploy components (cert-manager, tidb-operator, cluster-agent etc.)
e2e: cleanup-e2e e2e-cli local-build-image prepare-images
	cd ./test/e2e && e2e run

cleanup-e2e:
	kind delete cluster --name kind

### 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/cmd/golangci-lint@v1.64.8)

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

### 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
