# FleetDM Stack - Local Kubernetes Deployment
# Requires: helm, kubectl, docker; optional: kind or minikube

RELEASE_NAME ?= fleetdm-stack
NAMESPACE ?= fleetdm
CLUSTER_TYPE ?= kind
FLEET_PORT ?= 8585

.PHONY: cluster install uninstall deps verify clean port-forward

cluster:
	@echo "Creating local Kubernetes cluster ($(CLUSTER_TYPE))..."
ifeq ($(CLUSTER_TYPE),kind)
	@command -v kind >/dev/null 2>&1 || { echo "Install kind: https://kind.sigs.k8s.io/"; exit 1; }
	kind create cluster --name fleetdm --wait 2m || true
	@echo "Installing nginx ingress controller..."
	kubectl apply -f https://raw.githubusercontent.com/kubernetes/ingress-nginx/main/deploy/static/provider/kind/deploy.yaml
	kubectl wait --namespace ingress-nginx --for=condition=ready pod -l app.kubernetes.io/component=controller --timeout=120s
else
	@command -v minikube >/dev/null 2>&1 || { echo "Install minikube: https://minikube.sigs.k8s.io/"; exit 1; }
	minikube start
	minikube addons enable ingress
endif
	@echo "Cluster ready. Run 'make install' to deploy FleetDM stack."

deps:
	helm dependency update fleetdm-stack/

tls-certs:
	@mkdir -p fleetdm-stack/certs && \
	if [ ! -f fleetdm-stack/certs/cert.pem ]; then \
		openssl req -x509 -nodes -days 365 -newkey rsa:2048 \
			-keyout fleetdm-stack/certs/key.pem -out fleetdm-stack/certs/cert.pem \
			-subj "/CN=fleet.localhost"; \
		echo "Generated TLS certs in fleetdm-stack/certs/"; \
	fi

install: deps tls-certs
	@echo "Creating namespace $(NAMESPACE)..."
	kubectl create namespace $(NAMESPACE) --dry-run=client -o yaml | kubectl apply -f -
	@echo "Installing FleetDM stack..."
	helm upgrade --install $(RELEASE_NAME) fleetdm-stack/ \
		--namespace $(NAMESPACE)
	@echo "Installation complete. Run 'make verify' to check status."

uninstall:
	@echo "Removing FleetDM stack..."
	helm uninstall $(RELEASE_NAME) --namespace $(NAMESPACE) || true
	kubectl delete namespace $(NAMESPACE) --timeout=120s || true
	@echo "Uninstall complete."

port-forward:
	@echo "Forwarding Fleet UI to https://0.0.0.0:$(FLEET_PORT) ..."
	@echo "Press Ctrl+C to stop."
	kubectl port-forward --address 0.0.0.0 svc/fleetdm-stack-service $(FLEET_PORT):8080 -n $(NAMESPACE)

verify:
	@echo "Verifying FleetDM, MySQL, and Redis..."
	@echo ""
	@echo "=== Pods ==="
	kubectl get pods -n $(NAMESPACE) -o wide
	@echo ""
	@echo "=== Services ==="
	kubectl get svc -n $(NAMESPACE)
	@echo ""
	@echo "=== Ingress ==="
	kubectl get ingress -n $(NAMESPACE) 2>/dev/null || echo "  (no ingress)"
	@echo ""
	@echo "Access Fleet UI:"
	@echo "  make port-forward    # then open https://localhost:$(FLEET_PORT)"
	@echo "  (or change port: make port-forward FLEET_PORT=9090)"

clean: uninstall
ifeq ($(CLUSTER_TYPE),kind)
	@echo "Deleting Kind cluster..."
	kind delete cluster --name fleetdm || true
else
	@echo "Stopping minikube..."
	-minikube stop
endif
