PWD = $(shell pwd)
GO_VERSION ?= 1.20.6
ACTIONLINT_VERSION ?= latest
ACTIONLINT = $(PWD)/bin/actionlint
GOPATH=$(PWD)
GOBIN=$(PWD)/bin
WORKSPACE ?= $(PWD)/work
KSI_KUBECONFIG_PATH ?= $(WORKSPACE)/kind-kubeconfig
KCM_CHART_VERSION ?= 1.0.0
CONTAINER_WORKDIR ?= /ksi/work
KUBEMOUNT ?= $(CONTAINER_WORKDIR)/kubeconfig
KIND_NAME ?= ksi-kind
KIND_INSTALLED ?= $(shell kind get clusters 2>/dev/null | grep $(KIND_NAME))
KIND ?= False
SI_BINARIES_DIR ?= $(PWD)/bin
PLATFORM ?= $(shell uname -s | tr '[:upper:]' '[:lower:]')
SUPPORT_BUNDLE_VERSION ?= 0.117.0
SUPPORT_BUNDLE_DOWNLOAD_URL ?= "https://github.com/replicatedhq/troubleshoot/releases/download/v$(SUPPORT_BUNDLE_VERSION)/support-bundle_$(PLATFORM)_amd64.tar.gz"

# Default target
.DEFAULT_GOAL := help

# Help target
.PHONY: help
help:
	@echo "K0rdent System Integration (KSI) Makefile"
	@echo "=========================================="
	@echo ""
	@echo "Available targets:"
	@echo ""
	@echo "Setup & Dependencies:"
	@echo "  check-uv                  - Check and install uv if needed"
	@echo "  install-venv              - Create/update Python virtual environment using uv"
	@echo "  sync-dependencies        - Sync Python dependencies (requires active venv)"
	@echo "  check-go                  - Check and install Go $(GO_VERSION) if needed"
	@echo "  check-kind                - Check and install Kind if needed"
	@echo "  download-support-bundle   - Download troubleshoot support-bundle tool"
	@echo ""
	@echo "Docker & Building:"
	@echo "  build                     - Build KSI Docker image with current git commit tag"
	@echo "  docker-shell              - Start interactive shell in KSI Docker container"
	@echo ""
	@echo "Kind Cluster Management:"
	@echo "  create-kind-cluster       - Create Kind cluster with kubeconfig at $(WORKSPACE)/kind-kubeconfig"
	@echo "  delete-kind-cluster       - Delete Kind cluster and cleanup kubeconfig files"
	@echo ""
	@echo "K0rdent Installation & Testing:"
	@echo "  test-install-enterprise   - Install K0rdent enterprise edition on Kind cluster"
	@echo "  test-backup-ondemand      - Run on-demand backup test locally (requires KUBECONFIG and active venv)"
	@echo ""
	@echo "Support & Diagnostics:"
	@echo "  test-gather-support-dump  - Gather support bundle from cluster"
	@echo "  test-render-config        - Render configuration for support bundle"
	@echo ""
	@echo "Code Quality:"
	@echo "  install-actionlint        - Install actionlint for GitHub Actions validation"
	@echo "  run-actionlint            - Run actionlint on GitHub Actions workflows"
	@echo ""
	@echo "Cleanup:"
	@echo "  clean                     - Clean up by deleting Kind cluster"
	@echo ""
	@echo "Variables:"
	@echo "  WORKSPACE                 - Working directory (default: $(PWD)/work)"
	@echo "  KCM_CHART_VERSION         - K0rdent chart version (default: $(KCM_CHART_VERSION))"
	@echo "  KIND_NAME                 - Kind cluster name (default: $(KIND_NAME))"
	@echo "  GO_VERSION                - Go version to install (default: $(GO_VERSION))"
	@echo ""
	@echo "Examples:"
	@echo "  make create-kind-cluster                    # Create Kind cluster"
	@echo "  make test-install-enterprise                # Install K0rdent enterprise"
	@echo "  make test-gather-support-dump               # Gather support bundle"
	@echo "  make KCM_CHART_VERSION=1.1.0 test-install-enterprise  # Install specific version"
	@echo ""

work:
	@mkdir -p $(WORKSPACE)

download-support-bundle:
	curl -L $(SUPPORT_BUNDLE_DOWNLOAD_URL) | tar xz -C $(SI_BINARIES_DIR) support-bundle
	chmod +x $(SI_BINARIES_DIR)/support-bundle

check-kind:
	@which kind > /dev/null && echo "Kind is already installed" || ( \
		if [ "$(shell uname)" = "Darwin" ]; then \
			echo "Running on macOS"; \
			[ "$(shell uname -m)" = x86_64 ] && curl -Lo ./kind https://kind.sigs.k8s.io/dl/v0.27.0/kind-darwin-amd64; \
			[ "$(shell uname -m)" = arm64 ] && curl -Lo ./kind https://kind.sigs.k8s.io/dl/v0.27.0/kind-darwin-arm64; \
			chmod +x ./kind; \
			mv ./kind /usr/local/bin/kind; \
		elif [ "$(shell uname)" = "Linux" ]; then \
			echo "Running on Linux"; \
			[ "$(shell uname -m)" = x86_64 ] && curl -Lo ./kind https://kind.sigs.k8s.io/dl/v0.27.0/kind-linux-amd64; \
			[ "$(shell uname -m)" = aarch64 ] && curl -Lo ./kind https://kind.sigs.k8s.io/dl/v0.27.0/kind-linux-arm64; \
			chmod +x ./kind; \
			mv ./kind /usr/local/bin/kind; \
		else \
			echo "Unsupported OS"; \
			exit 1; \
		fi; \
		which kind > /dev/null || ( \
			echo "Kind installation failed"; \
			exit 1; \
		); \
	)


check-go:
	@which go > /dev/null || ( \
		echo "Go not installed. Installing Go $(GO_VERSION)..."; \
		wget https://golang.org/dl/go$(GO_VERSION).linux-amd64.tar.gz; \
		sudo tar -C /usr/local -xzf go$(GO_VERSION).linux-amd64.tar.gz; \
		rm go$(GO_VERSION).linux-amd64.tar.gz; \
	)
	@echo "Go installed"

install-actionlint: check-go
	@GOPATH=$(GOPATH) GOBIN=$(GOBIN) go install github.com/rhysd/actionlint/cmd/actionlint@$(ACTIONLINT_VERSION)

run-actionlint: install-actionlint
	@$(ACTIONLINT) -verbose -ignore SC

build:
	docker build --tag k0rdent/ksi:$(shell git rev-parse --short HEAD) .
	docker tag k0rdent/ksi:$(shell git rev-parse --short HEAD) k0rdent/ksi:latest

.PHONY: check-uv
check-uv:
	@which uv > /dev/null && echo "uv is already installed" || ( \
		echo "uv not installed. Installing uv..."; \
		curl -LsSf https://astral.sh/uv/install.sh | sh; \
		echo "uv installed. You may need to restart your shell."; \
	)

install-venv: check-uv
	uv sync
	@echo
	@echo "The new venv can now be activated. (example: source .venv/bin/activate)"

docker-shell:
	docker run -it --rm \
	-v $(WORKSPACE):$(CONTAINER_WORKDIR) \
	$(if $(KIND_INSTALLED),--network kind) \
	k0rdent/ksi:latest

test-install-enterprise:
	docker run -it  \
	-e KUBECONFIG=$(KSI_KUBECONFIG_PATH)$(if $(KIND_INSTALLED),-kind-network) \
	-e KCM_CHART_VERSION=$(KCM_CHART_VERSION) \
	-e KCM_SOURCE="enterprise" \
	-v $(WORKSPACE):$(CONTAINER_WORKDIR) \
	$(if $(KIND_INSTALLED),--network kind) \
	k0rdent/ksi:latest \
	pytest /ksi/si_tests/tests/bootstrap/test_install_kcm.py

test-gather-support-dump:
	docker run -it  \
	-v $(WORKSPACE):$(CONTAINER_WORKDIR) \
	-e KSI_KUBECONFIG_PATH=$(KSI_KUBECONFIG_PATH)$(if $(KIND_INSTALLED),-kind-network) \
	-e ARTIFACTS_DIR=$(CONTAINER_WORKDIR) \
	$(if $(KIND_INSTALLED),--network kind) \
	k0rdent/ksi:latest \
	pytest /ksi/si_tests/tests/supportdump/test_supportdump.py::test_gather_support_dump
	echo "Support bundle created at $(WORKSPACE)"

test-render-config:
	docker run -it  \
	-v $(WORKSPACE):$(CONTAINER_WORKDIR) \
	-e KSI_KUBECONFIG_PATH=$(KSI_KUBECONFIG_PATH)$(if $(KIND_INSTALLED),-kind-network) \
	-e ARTIFACTS_DIR=$(CONTAINER_WORKDIR) \
	$(if $(KIND_INSTALLED),--network kind) \
	k0rdent/ksi:latest \
	pytest /ksi/si_tests/tests/supportdump/test_supportdump.py::test_render_config

create-kind-cluster: check-kind work
	kind create cluster --name ksi-kind --kubeconfig $(KSI_KUBECONFIG_PATH)
	sed "s/127.0.0.1:[0-9]\{5\}/ksi-kind-control-plane:6443/g" $(KSI_KUBECONFIG_PATH) > $(KSI_KUBECONFIG_PATH)-kind-network

delete-kind-cluster: check-kind work
	kind delete cluster --name ksi-kind
	rm -f $(KSI_KUBECONFIG_PATH)-kind-network
	rm -f $(KSI_KUBECONFIG_PATH)
	@echo "Kind cluster deleted"

clean: delete-kind-cluster

.PHONY: sync-dependencies

sync-dependencies:
	@echo "Using Python: $$(which python3)"
	@test -n "$$VIRTUAL_ENV" || (echo "Please activate your virtualenv first." && exit 1)
	@python3 tools/sync-dependencies.py

test-backup-ondemand:
	@echo "Running on-demand backup test locally"
	@test -n "$$VIRTUAL_ENV" || (echo "Please activate your virtualenv first with: . .venv/bin/activate" && exit 1)
	@test -n "$(KUBECONFIG)" || (echo "Please set KUBECONFIG environment variable to your kubeconfig path" && exit 1)
	@test -f "$(KUBECONFIG)" || (echo "Kubeconfig file not found: $(KUBECONFIG)" && exit 1)
	@echo "Using kubeconfig: $(KUBECONFIG)"
	@echo "Using default storage location and auto-generated backup name"
	KUBECONFIG_PATH=$(KUBECONFIG) \
	py.test si_tests/tests/lcm/backup-restore/test_ondemand_backup.py -v

