# Longhorn Storage Management
# Commands for installing and managing Longhorn distributed storage

# Include common variables and functions
include common/Makefile

# Longhorn configuration
# Using common namespace variables from common/Makefile

.PHONY: longhorn-help
longhorn-help:
	@echo ""
	@echo "$(COLOR_BOLD)Longhorn Storage Commands:$(COLOR_RESET)"
	@echo "  make longhorn-install        - Install Longhorn (requires deps installed via Ansible)"
	@echo "  make longhorn-update         - Update Longhorn with new values"
	@echo "  make longhorn-install-all    - Full installation with dependency check"
	@echo "  make longhorn-status         - Check Longhorn status"
	@echo "  make longhorn-uninstall      - Uninstall Longhorn (WARNING: deletes all data)"
	@echo ""
	@echo "$(COLOR_YELLOW)Note:$(COLOR_RESET) Before installing, prepare worker nodes:"
	@echo "  cd ../.. && make longhorn-prepare-nodes"

.PHONY: longhorn-check-deps
longhorn-check-deps:
	@echo ""
	@echo "$(COLOR_BOLD)=== Checking Longhorn dependencies ===$(COLOR_RESET)"
	@echo ""
	@echo "Longhorn requires $(COLOR_BOLD)open-iscsi$(COLOR_RESET) and $(COLOR_BOLD)nfs-common$(COLOR_RESET) on worker nodes."
	@echo "These dependencies should be installed via Ansible."
	@echo ""
	@echo "$(COLOR_YELLOW)If not installed yet, run from infra/ directory:$(COLOR_RESET)"
	@echo "  cd ../.. && make longhorn-prepare-nodes"
	@echo ""
	@echo "Press Ctrl+C to cancel, or wait 5 seconds to continue..."
	$(call sleep_seconds,5)

.PHONY: longhorn-check-repo
longhorn-check-repo:
	$(call print_info,Checking Longhorn Helm repository...)
ifeq ($(DETECTED_OS),Windows)
	@powershell -NoProfile -Command "$$curDir = [System.IO.Directory]::GetCurrentDirectory(); $$kubeconfig = [System.IO.Path]::GetFullPath([System.IO.Path]::Combine($$curDir, '$(KUBECONFIG_REL)')); $$env:KUBECONFIG = $$kubeconfig; $$repoExists = helm repo list 2>&1 | Select-String -Pattern 'longhorn'; if (-not $$repoExists) { Write-Host 'Adding Longhorn Helm repository...'; $$result = helm repo add longhorn https://charts.longhorn.io --force-update 2>&1; if ($$LASTEXITCODE -ne 0) { Write-Host 'Error adding repository:'; Write-Host $$result; Write-Host ''; Write-Host 'Troubleshooting:'; Write-Host '  1. Check your Helm version: helm version'; Write-Host '  2. Update Helm if needed'; Write-Host '  3. Check network/proxy settings'; Write-Host '  4. Try manually: helm repo add longhorn https://charts.longhorn.io'; exit 1 }; helm repo update longhorn } else { Write-Host 'Longhorn repository already exists, updating...'; helm repo update longhorn }"
else
	@if ! $(HELM) repo list 2>/dev/null | grep -q "longhorn"; then \
		echo "Adding Longhorn Helm repository..."; \
		$(HELM) repo add longhorn https://charts.longhorn.io --force-update || \
			($(call print_warning,Failed to add Longhorn repository.) && \
			 echo "$(COLOR_YELLOW)Troubleshooting:$(COLOR_RESET)" && \
			 echo "  1. Check your Helm version: helm version" && \
			 echo "  2. Update Helm if needed" && \
			 echo "  3. Check network/proxy settings" && \
			 echo "  4. Try manually: helm repo add longhorn https://charts.longhorn.io" && \
			 exit 1); \
		$(HELM) repo update longhorn; \
	else \
		echo "Longhorn repository already exists, updating..."; \
		$(HELM) repo update longhorn; \
	fi
endif

.PHONY: longhorn-install
longhorn-install: install-namespaces longhorn-check-repo
	$(call print_info,Installing Longhorn via helmfile...)
	$(call run_helmfile,longhorn/helmfile.yaml,sync)
	$(call print_info,Waiting for Longhorn to be ready...)
	@$(KUBECTL) -n $(LONGHORN_NAMESPACE) rollout status daemonset/longhorn-manager --timeout=5m
	@$(KUBECTL) -n $(LONGHORN_NAMESPACE) rollout status daemonset/longhorn-csi-plugin --timeout=5m || echo "longhorn-csi-plugin DaemonSet not ready yet (will be created by longhorn-driver-deployer)"
	@$(KUBECTL) -n $(LONGHORN_NAMESPACE) rollout status deployment/longhorn-ui --timeout=5m
	@$(KUBECTL) -n $(LONGHORN_NAMESPACE) rollout status deployment/longhorn-driver-deployer --timeout=5m
	@$(MAKE) longhorn-status
	$(call print_success,Longhorn installed successfully!)

.PHONY: longhorn-update
longhorn-update:
	$(call print_info,Updating Longhorn with new values via helmfile...)
	$(call run_helmfile,longhorn/helmfile.yaml,sync)
	$(call print_info,Waiting for Longhorn to be ready...)
	@$(KUBECTL) -n $(LONGHORN_NAMESPACE) rollout status daemonset/longhorn-manager --timeout=5m
	@$(KUBECTL) -n $(LONGHORN_NAMESPACE) rollout status daemonset/longhorn-csi-plugin --timeout=5m || echo "longhorn-csi-plugin DaemonSet not ready yet"
	@$(KUBECTL) -n $(LONGHORN_NAMESPACE) rollout status deployment/longhorn-ui --timeout=5m
	@$(KUBECTL) -n $(LONGHORN_NAMESPACE) rollout status deployment/longhorn-driver-deployer --timeout=5m
	$(call print_success,Longhorn updated!)

.PHONY: longhorn-install-storage
longhorn-install-storage:
	$(call print_info,Creating Longhorn storage classes and recurring jobs...)
ifeq ($(DETECTED_OS),Windows)
	@$(KUBECTL) apply -f longhorn/manifests/storageclass-longhorn.yaml 2>nul || echo "StorageClass may already exist"
	@$(KUBECTL) apply -f longhorn/manifests/storageclass-longhorn-retain.yaml
	@$(KUBECTL) apply -f longhorn/manifests/storageclass-longhorn-2replicas.yaml
	@$(KUBECTL) apply -f longhorn/manifests/storageclass-longhorn-3replicas.yaml
	@$(KUBECTL) apply -f longhorn/manifests/recurring-jobs.yaml
else
	@$(KUBECTL) apply -f longhorn/manifests/storageclass-longhorn.yaml 2>/dev/null || true
	@$(KUBECTL) apply -f longhorn/manifests/storageclass-longhorn-retain.yaml
	@$(KUBECTL) apply -f longhorn/manifests/storageclass-longhorn-2replicas.yaml
	@$(KUBECTL) apply -f longhorn/manifests/storageclass-longhorn-3replicas.yaml
	@$(KUBECTL) apply -f longhorn/manifests/recurring-jobs.yaml
endif
	@echo ""
	@echo "$(COLOR_BOLD)Storage classes created:$(COLOR_RESET)"
ifeq ($(DETECTED_OS),Windows)
	@$(KUBECTL) get storageclass | powershell -NoProfile -Command "$$input = $$input | Out-String; if ($$input -match 'longhorn') { Write-Output $$input } else { Write-Output 'Done' }"
else
	@$(KUBECTL) get storageclass | grep longhorn || echo "Done"
endif

.PHONY: longhorn-install-all
longhorn-install-all: longhorn-check-deps longhorn-install
	$(call print_info,Waiting 30 seconds for Longhorn initialization...)
	$(call sleep_seconds,30)
	@$(MAKE) longhorn-install-storage
	@echo ""
	@echo "$(COLOR_GREEN)$(COLOR_BOLD)===================================$(COLOR_RESET)"
	@echo "$(COLOR_GREEN)$(COLOR_BOLD)  Longhorn installation complete!  $(COLOR_RESET)"
	@echo "$(COLOR_GREEN)$(COLOR_BOLD)===================================$(COLOR_RESET)"
	@echo ""
	@echo "Next steps:"
	@echo "  1. Check status: $(COLOR_BOLD)make longhorn-status$(COLOR_RESET)"
	@echo ""

.PHONY: longhorn-status
longhorn-status:
	@echo ""
	@echo "$(COLOR_BOLD)=== Longhorn Manager Status ===$(COLOR_RESET)"
	@$(KUBECTL) -n $(LONGHORN_NAMESPACE) get pods -l app=longhorn-manager
	@echo ""
	@echo "$(COLOR_BOLD)=== Longhorn UI Status ===$(COLOR_RESET)"
	@$(KUBECTL) -n $(LONGHORN_NAMESPACE) get pods -l app=longhorn-ui
	@echo ""
	@echo "$(COLOR_BOLD)=== Longhorn Driver Status ===$(COLOR_RESET)"
	@$(KUBECTL) -n $(LONGHORN_NAMESPACE) get pods -l app=longhorn-driver-deployer
	@echo ""
	@echo "$(COLOR_BOLD)=== CSI Pods ===$(COLOR_RESET)"
	@$(KUBECTL) -n $(LONGHORN_NAMESPACE) get pods -l app=csi-attacher
	@$(KUBECTL) -n $(LONGHORN_NAMESPACE) get pods -l app=csi-provisioner
	@$(KUBECTL) -n $(LONGHORN_NAMESPACE) get pods -l app=csi-resizer
	@$(KUBECTL) -n $(LONGHORN_NAMESPACE) get pods -l app=csi-snapshotter
	@echo ""
	@echo "$(COLOR_BOLD)=== Longhorn Nodes ===$(COLOR_RESET)"
	@$(KUBECTL) -n $(LONGHORN_NAMESPACE) get nodes.longhorn.io || echo "Nodes CRD not ready yet"
	@echo ""
	@echo "$(COLOR_BOLD)=== Storage Classes ===$(COLOR_RESET)"
	@$(KUBECTL) get storageclass || echo "No Longhorn storage classes"
	@echo ""

.PHONY: longhorn-uninstall
longhorn-uninstall:
	$(call print_warning,This will delete ALL data stored in Longhorn!)
	@echo "Press Ctrl+C to cancel, or wait 10 seconds to continue..."
	$(call sleep_seconds,10)
	$(call print_info,Removing storage classes and recurring jobs...)
	-@$(KUBECTL) delete -f longhorn/manifests/storageclass-longhorn.yaml 2>/dev/null || true
	-@$(KUBECTL) delete -f longhorn/manifests/storageclass-longhorn-retain.yaml 2>/dev/null || true
	-@$(KUBECTL) delete -f longhorn/manifests/storageclass-longhorn-2replicas.yaml 2>/dev/null || true
	-@$(KUBECTL) delete -f longhorn/manifests/storageclass-longhorn-3replicas.yaml 2>/dev/null || true
	-@$(KUBECTL) delete -f longhorn/manifests/recurring-jobs.yaml 2>/dev/null || true
	$(call print_info,Uninstalling Longhorn...)
	$(call run_helmfile,longhorn/helmfile.yaml,destroy) || true
	@echo "Waiting for resources to be cleaned up..."
	$(call sleep_seconds,30)
	$(call print_success,Uninstall complete.)
