# ENVTEST_K8S_VERSION refers to the version of kubebuilder assets to be downloaded by envtest binary.
ENVTEST_K8S_VERSION = 1.23

# Get the currently used golang install path (in GOPATH/bin, unless GOBIN is set)
ifeq (,$(shell go env GOBIN))
GOBIN=$(shell go env GOPATH)/bin
else
GOBIN=$(shell go env GOBIN)
endif
LINT_PACKAGE_LIST  := go list ./...| grep -vE "docs|proto|test"
LINT_PACKAGES  ?= $$($(LINT_PACKAGE_LIST))

# Setting SHELL to bash allows bash commands to be executed by recipes.
# This is a requirement for 'setup-envtest.sh' in the test target.
# Options are set to exit when a recipe line exits non-zero or a piped command fails.
SHELL = /usr/bin/env bash -o pipefail
.SHELLFLAGS = -ec
COMMIT := $(shell git rev-parse HEAD)
# Image URL to use all building/pushing image targets
IMG ?= ${REGISTRY}:${COMMIT}

GOLANGCI_LINT_VERSION ?= v2.1.6

include Makefile.common

.PHONY: all
all: build

##@ General

# The help target prints out all targets with their descriptions organized
# beneath their categories. The categories are represented by '##@' and the
# target descriptions by '##'. The awk commands is responsible for reading the
# entire set of makefiles included in this invocation, looking for lines of the
# file as xyz: ## something, and then pretty-format the target and help. Then,
# if there's a line with ##@ something, that gets pretty-printed as a category.
# More info on the usage of ANSI control characters for terminal formatting:
# https://en.wikipedia.org/wiki/ANSI_escape_code#SGR_parameters
# More info on the awk command:
# http://linuxcommand.org/lc3_adv_awk.php

.PHONY: help
help: ## Display this help.
	@awk 'BEGIN {FS = ":.*##"; printf "\nUsage:\n  make \033[36m<target>\033[0m\n"} /^[a-zA-Z_0-9-]+:.*?##/ { printf "  \033[36m%-15s\033[0m %s\n", $$1, $$2 } /^##@/ { printf "\n\033[1m%s\033[0m\n", substr($$0, 5) } ' $(MAKEFILE_LIST)

##@ Development

.PHONY: vendor
vendor:
	hack/vendor.sh

.PHONY: manifests
manifests: controller-gen ## Generate WebhookConfiguration, ClusterRole and CustomResourceDefinition objects.
	$(CONTROLLER_GEN) rbac:roleName=o11y-agent-control-server-role crd webhook paths="./..." output:crd:artifacts:config=config/crd/bases

.PHONY: generate
generate: controller-gen ## Generate code containing DeepCopy, DeepCopyInto, and DeepCopyObject method implementations.
	$(CONTROLLER_GEN) object:headerFile="hack/boilerplate.go.txt" paths="./..."

.PHONY: add_ut_file
add_ut_file: ## Add empty test file to make pkg go file be calculated into ut coverage, mainly for CI, no need to run locally.
	cat build/ci/add_ut_file.sh

.PHONY: ci_ut
ci_ut: add_ut_file vendor ## UT for CI, do not run locally, run `make ut` instead.
	go install github.com/axw/gocov/gocov@latest
	go install github.com/jstemmer/go-junit-report@latest
	go install github.com/AlekSi/gocov-xml@latest
	$(GO) install gotest.tools/gotestsum@latest
	@-(gotestsum --junitfile ./unit-tests.xml --packages=${PACKAGES})
	-go test -v ${PACKAGES} -coverprofile=cover.out
	gocov convert cover.out | gocov-xml > coverage.xml

.PHONY: test
test: ## Run unit test against code.
	./control.sh unittest

##@ Build

.PHONY: build
build:
	go mod tidy -v
	CGO_ENABLED=0 go build -buildmode=pie -ldflags "-X main.buildTime=$(shell date -u '+%Y-%m-%d_%I:%M:%S%p') -X main.gitHash=$(shell git rev-parse HEAD) -X main.gitBranch=$(shell git branch --show-current)" -o build/bin/agent-control-server main.go

docker-build:
	IMG=${IMG} VENDOR=${VENDOR} build/package/agent-control-server-d/build.sh

docker-push:
	docker push ${IMG}

.PHONY: run
run: manifests generate lint ## Run a controller from your host.
	go run ./main.go

##@ Deployment

ifndef ignore-not-found
  ignore-not-found = false
endif

.PHONY: install
install: manifests kustomize ## Install CRDs into the K8s cluster specified in ~/.kube/config.
	$(KUSTOMIZE) build config/crd | kubectl apply -f -

.PHONY: uninstall
uninstall: manifests kustomize ## Uninstall CRDs from the K8s cluster specified in ~/.kube/config. Call with ignore-not-found=true to ignore resource not found errors during deletion.
	$(KUSTOMIZE) build config/crd | kubectl delete --ignore-not-found=$(ignore-not-found) -f -

##@ Build Dependencies

## Location to install dependencies to
LOCALBIN ?= $(shell pwd)/bin
$(LOCALBIN):
	mkdir -p $(LOCALBIN)

## Tool Binaries
KUSTOMIZE ?= $(LOCALBIN)/kustomize
CONTROLLER_GEN ?= $(LOCALBIN)/controller-gen
ENVTEST ?= $(LOCALBIN)/setup-envtest

## Tool Versions
KUSTOMIZE_VERSION ?= v4.5.5
CONTROLLER_TOOLS_VERSION ?= v0.17.3

kustomize: $(KUSTOMIZE) ## Download kustomize locally if necessary. If wrong version is installed, it will be removed before downloading.
$(KUSTOMIZE): $(LOCALBIN)
	@if test -x $(LOCALBIN)/kustomize && ! $(LOCALBIN)/kustomize version | grep -q $(KUSTOMIZE_VERSION); then \
		echo "$(LOCALBIN)/kustomize version is not expected $(KUSTOMIZE_VERSION). Removing it before installing."; \
		rm -rf $(LOCALBIN)/kustomize; \
	fi
	test -s $(LOCALBIN)/kustomize || GOBIN=$(LOCALBIN) GO111MODULE=on go install sigs.k8s.io/kustomize/kustomize/v4@$(KUSTOMIZE_VERSION)

.PHONY: controller-gen
controller-gen: $(CONTROLLER_GEN) ## Download controller-gen locally if necessary.
$(CONTROLLER_GEN): $(LOCALBIN)
	test -s $(CONTROLLER_GEN) || GOBIN=$(LOCALBIN) go install sigs.k8s.io/controller-tools/cmd/controller-gen@$(CONTROLLER_TOOLS_VERSION)

.PHONY: lint
lint:
	gofmt -r 'interface{} -> any' -w .
	goimports-reviser -project-name "github.com/tidbcloud/observability/agent-control-server" ./...
	gofumpt -w .
	golangci-lint run --fix -v $$($(LINT_PACKAGES)) --config .golangci.yml

.PHONY: dev-tools
dev-tools:
	test -s golangci-lint || $(GO) install github.com/golangci/golangci-lint/v2/cmd/golangci-lint@$(GOLANGCI_LINT_VERSION)
	test -s goimports-reviser || $(GO) install github.com/incu6us/goimports-reviser/v3@latest
	test -s gofumpt || $(GO) install mvdan.cc/gofumpt@v0.5.0
