.PHONY: init plan apply destroy kubeconfig talosconfig argocd-password bootstrap decrypt post-apply

SECRET=dumpnet/cluster
TF_DIR=terraform
SOPS_FILES=controlplane.yaml worker.yaml talosconfig

# Cluster infrastructure
init:
	cd $(TF_DIR) && terraform init

plan:
	cd $(TF_DIR) && terraform plan

apply:
	cd $(TF_DIR) && terraform apply

destroy:
	cd $(TF_DIR) && terraform destroy

# Bootstrap ArgoCD app of apps (run once after cluster is up)
bootstrap:
	kubectl apply -f apps/apps.yaml

# Credentials
talosconfig:
	aws secretsmanager get-secret-value --secret-id $(SECRET) \
	  --query SecretString --output text | python3 -c \
	  "import sys,json; print(json.load(sys.stdin)['talosconfig'])" \
	  > /tmp/talosconfig-dumpnet
	talosctl config merge /tmp/talosconfig-dumpnet
	rm /tmp/talosconfig-dumpnet
	talosctl config context dumpnet

kubeconfig:
	aws secretsmanager get-secret-value --secret-id $(SECRET) \
	  --query SecretString --output text | python3 -c \
	  "import sys,json; print(json.load(sys.stdin)['kubeconfig'])" \
	  > /tmp/kubeconfig-dumpnet
	KUBECONFIG=~/.kube/config:/tmp/kubeconfig-dumpnet kubectl config view --flatten > /tmp/merged
	mv /tmp/merged ~/.kube/config
	rm /tmp/kubeconfig-dumpnet
	kubectl config use-context admin@dumpnet

argocd-password:
	@aws secretsmanager get-secret-value --secret-id $(SECRET) \
	  --query SecretString --output text | python3 -c \
	  "import sys,json; print(json.load(sys.stdin)['argocd_admin_password'])"

# Decrypt sensitive files to /tmp for one-off talosctl use
# Files are never decrypted in the repo directory
decrypt:
	@for f in $(SOPS_FILES); do \
	  if [ -f $$f ]; then \
	    echo "Decrypting $$f to /tmp/$$f..."; \
	    sops -d $$f > /tmp/$$f; \
	  fi; \
	done
	@echo "Decrypted files are in /tmp/ - they will not persist after reboot"

# Run all post-apply steps (run once after fresh cluster creation)
post-apply:
	scripts/post-apply.sh
