## GlitchTip Management
## GlitchTip через официальный Helm chart

# Include common variables and functions
include common/Makefile

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

.PHONY: glitchtip-help
glitchtip-help:
	@echo ""
	@echo "$(COLOR_BOLD)GlitchTip Commands:$(COLOR_RESET)"
	@echo "  make glitchtip-install         - Install GlitchTip"
	@echo "  make glitchtip-update         - Update GlitchTip with new values"
	@echo "  make glitchtip-uninstall       - Uninstall GlitchTip"
	@echo "  make glitchtip-create-secret   - Create secrets (SECRET_KEY, DATABASE_URL)"
	@echo "  make glitchtip-create-service-secret - Create Sentry DSN secret for a service"
	@echo "  make glitchtip-update-secret   - Update secrets (SECRET_KEY, DATABASE_URL)"
	@echo "  make glitchtip-delete-secret   - Delete secrets"
	@echo "  make glitchtip-get-secret      - Get secret info"
	@echo "  make glitchtip-status          - Check GlitchTip status"
	@echo ""
	@echo "$(COLOR_YELLOW)Note:$(COLOR_RESET) Before installing:"
	@echo "  1. PostgreSQL cluster pg-public must be running"
	@echo "  2. Create secrets: make glitchtip-create-secret"
	@echo "  3. Prepare nodes: cd ../.. && make k8s-prepare-nodes"

.PHONY: glitchtip-check-postgres
glitchtip-check-postgres:
	$(call check_postgres_cluster)

.PHONY: glitchtip-create-secret
glitchtip-create-secret:
	$(call print_info,Creating namespace $(GLITCHTIP_NAMESPACE) if not exists...)
	@$(KUBECTL) apply -f glitchtip/manifests/namespace.yaml
	@echo ""
	@echo "$(COLOR_YELLOW)Creating GlitchTip secrets...$(COLOR_RESET)"
	@echo "$(COLOR_YELLOW)You will be prompted for:$(COLOR_RESET)"
	@echo "  1. SECRET_KEY (Django secret key - generate a random string)"
	@echo "  2. PostgreSQL password for glitchtip user"
	@echo ""
	@echo "$(COLOR_YELLOW)Note:$(COLOR_RESET) Redis is not required - GlitchTip uses built-in Valkey (Redis-compatible)"
	@echo ""
	@echo "$(COLOR_YELLOW)Enter SECRET_KEY (random string, e.g., use: openssl rand -hex 32):$(COLOR_RESET)"
ifeq ($(DETECTED_OS),Windows)
	@powershell -NoProfile -Command "$$secretKey = Read-Host -Prompt '> '; Write-Host ''; Write-Host '$(COLOR_YELLOW)Enter PostgreSQL password for glitchtip user:$(COLOR_RESET)'; $$pgPassSecure = Read-Host -AsSecureString -Prompt '> '; $$pgPass = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($$pgPassSecure)); $$pgPassEncoded = [System.Uri]::EscapeDataString($$pgPass); $$pgUrl = \"postgresql://glitchtip:$$pgPassEncoded@pg-public-ha.tech-postgres-databases.svc.cluster.local:5432/glitchtip?sslmode=require\"; $$curDir = [System.IO.Directory]::GetCurrentDirectory(); $$kubeconfig = [System.IO.Path]::GetFullPath([System.IO.Path]::Combine($$curDir, '$(KUBECONFIG_REL)')); $$env:KUBECONFIG = $$kubeconfig; kubectl -n $(GLITCHTIP_NAMESPACE) delete secret glitchtip-secrets --ignore-not-found=true 2>$$null; kubectl -n $(GLITCHTIP_NAMESPACE) create secret generic glitchtip-secrets --from-literal=SECRET_KEY=$$secretKey --from-literal=DATABASE_URL=$$pgUrl"
else
	@read -s -p "> " secretKey && echo "" && \
		echo "$(COLOR_YELLOW)Enter PostgreSQL password for glitchtip user:$(COLOR_RESET)" && \
		read -s -p "> " pgPass && echo "" && \
		pgPassEncoded=$$(echo -n "$$pgPass" | python3 -c "import sys, urllib.parse; print(urllib.parse.quote(sys.stdin.read()))" 2>/dev/null || echo -n "$$pgPass" | sed 's/:/%3A/g; s/@/%40/g; s/\//%2F/g; s/?/%3F/g; s/=/%3D/g') && \
		pgUrl="postgresql://glitchtip:$$pgPassEncoded@pg-public-ha.tech-postgres-databases.svc.cluster.local:5432/glitchtip?sslmode=require" && \
		$(KUBECTL) -n $(GLITCHTIP_NAMESPACE) delete secret glitchtip-secrets --ignore-not-found=true 2>/dev/null || true && \
		$(KUBECTL) -n $(GLITCHTIP_NAMESPACE) create secret generic glitchtip-secrets --from-literal=SECRET_KEY=$$secretKey --from-literal=DATABASE_URL=$$pgUrl
endif
	$(call print_success,Secret created!)
	@echo ""
	@echo "$(COLOR_YELLOW)Note:$(COLOR_RESET) Make sure the PostgreSQL user 'glitchtip' exists in pg-public cluster"
	@echo "  Connect to PostgreSQL and create user:"
	@echo "    CREATE USER glitchtip WITH PASSWORD 'your_password';"
	@echo "    CREATE DATABASE glitchtip OWNER glitchtip;"
	@echo "    GRANT ALL PRIVILEGES ON DATABASE glitchtip TO glitchtip;"

.PHONY: glitchtip-create-service-secret
glitchtip-create-service-secret:
	@echo ""
	@echo "$(COLOR_YELLOW)Creating Sentry DSN secret for a service...$(COLOR_RESET)"
ifeq ($(DETECTED_OS),Windows)
	@powershell -NoProfile -Command "$$serviceName = Read-Host -Prompt 'Enter Service Name (e.g. identity-service)'; if (-not $$serviceName) { Write-Host 'Error: Service Name is required'; exit 1 }; $$secretKey = Read-Host -Prompt 'Enter GlitchTip Secret Key (token)'; if (-not $$secretKey) { Write-Host 'Error: Secret Key is required'; exit 1 }; $$projectId = Read-Host -Prompt 'Enter Project ID'; if (-not $$projectId) { Write-Host 'Error: Project ID is required'; exit 1 }; $$dsn = 'http://' + $$secretKey + '@glitchtip-web.tech-glitchtip.svc.cluster.local/' + $$projectId; $$secretName = $$serviceName + '-sentry-secrets'; $$curDir = [System.IO.Directory]::GetCurrentDirectory(); $$kubeconfig = [System.IO.Path]::GetFullPath([System.IO.Path]::Combine($$curDir, '$(KUBECONFIG_REL)')); $$env:KUBECONFIG = $$kubeconfig; kubectl -n $(GLITCHTIP_NAMESPACE) delete secret $$secretName --ignore-not-found=true 2>$$null; kubectl -n $(GLITCHTIP_NAMESPACE) create secret generic $$secretName --from-literal=sentry-dsn=$$dsn; Write-Host ''; Write-Host ('✓ Secret ' + $$secretName + ' created in namespace $(GLITCHTIP_NAMESPACE)!'); Write-Host ('DSN: ' + $$dsn)"
else
	@read -p "Enter Service Name (e.g. identity-service): " serviceName; \
	if [ -z "$$serviceName" ]; then echo "$(COLOR_RED)Error: Service Name is required$(COLOR_RESET)"; exit 1; fi; \
	read -p "Enter GlitchTip Secret Key (token): " secretKey; \
	if [ -z "$$secretKey" ]; then echo "$(COLOR_RED)Error: Secret Key is required$(COLOR_RESET)"; exit 1; fi; \
	read -p "Enter Project ID: " projectId; \
	if [ -z "$$projectId" ]; then echo "$(COLOR_RED)Error: Project ID is required$(COLOR_RESET)"; exit 1; fi; \
	dsn="http://$${secretKey}@glitchtip-web.tech-glitchtip.svc.cluster.local/$$projectId"; \
	secretName="$${serviceName}-sentry-secrets"; \
	$(KUBECTL) -n $(GLITCHTIP_NAMESPACE) delete secret $$secretName --ignore-not-found=true 2>/dev/null || true; \
	$(KUBECTL) -n $(GLITCHTIP_NAMESPACE) create secret generic $$secretName --from-literal=sentry-dsn=$$dsn; \
	echo ""; \
	echo "$(COLOR_GREEN)✓ Secret $$secretName created in namespace $(GLITCHTIP_NAMESPACE)!$(COLOR_RESET)"; \
	echo "DSN: $$dsn"
endif

.PHONY: glitchtip-update-secret
glitchtip-update-secret:
	$(call print_info,Updating GlitchTip secrets...)
	@echo ""
	@echo "$(COLOR_YELLOW)You will be prompted for:$(COLOR_RESET)"
	@echo "  1. SECRET_KEY (Django secret key - generate a random string)"
	@echo "  2. PostgreSQL password for glitchtip user"
	@echo ""
	@echo "$(COLOR_YELLOW)Enter SECRET_KEY (random string, e.g., use: openssl rand -hex 32):$(COLOR_RESET)"
ifeq ($(DETECTED_OS),Windows)
	@powershell -NoProfile -Command "$$secretKey = Read-Host -Prompt '> '; Write-Host ''; Write-Host '$(COLOR_YELLOW)Enter PostgreSQL password for glitchtip user:$(COLOR_RESET)'; $$pgPassSecure = Read-Host -AsSecureString -Prompt '> '; $$pgPass = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($$pgPassSecure)); $$pgPassEncoded = [System.Uri]::EscapeDataString($$pgPass); $$pgUrl = \"postgresql://glitchtip:$$pgPassEncoded@pg-public-ha.tech-postgres-databases.svc.cluster.local:5432/glitchtip?sslmode=require\"; $$curDir = [System.IO.Directory]::GetCurrentDirectory(); $$kubeconfig = [System.IO.Path]::GetFullPath([System.IO.Path]::Combine($$curDir, '$(KUBECONFIG_REL)')); $$env:KUBECONFIG = $$kubeconfig; kubectl -n $(GLITCHTIP_NAMESPACE) delete secret glitchtip-secrets --ignore-not-found=true 2>$$null; kubectl -n $(GLITCHTIP_NAMESPACE) create secret generic glitchtip-secrets --from-literal=SECRET_KEY=$$secretKey --from-literal=DATABASE_URL=$$pgUrl"
else
	@read -s -p "> " secretKey && echo "" && \
		echo "$(COLOR_YELLOW)Enter PostgreSQL password for glitchtip user:$(COLOR_RESET)" && \
		read -s -p "> " pgPass && echo "" && \
		pgPassEncoded=$$(echo -n "$$pgPass" | python3 -c "import sys, urllib.parse; print(urllib.parse.quote(sys.stdin.read()))" 2>/dev/null || echo -n "$$pgPass" | sed 's/:/%3A/g; s/@/%40/g; s/\//%2F/g; s/?/%3F/g; s/=/%3D/g') && \
		pgUrl="postgresql://glitchtip:$$pgPassEncoded@pg-public-ha.tech-postgres-databases.svc.cluster.local:5432/glitchtip?sslmode=require" && \
		$(KUBECTL) -n $(GLITCHTIP_NAMESPACE) delete secret glitchtip-secrets --ignore-not-found=true 2>/dev/null || true && \
		$(KUBECTL) -n $(GLITCHTIP_NAMESPACE) create secret generic glitchtip-secrets --from-literal=SECRET_KEY=$$secretKey --from-literal=DATABASE_URL=$$pgUrl
endif
	$(call print_success,Secret updated!)

.PHONY: glitchtip-delete-secret
glitchtip-delete-secret:
	$(call print_warning,This will delete the glitchtip-secrets secret!)
	@echo "Press Ctrl+C to cancel, or wait 5 seconds to continue..."
	$(call sleep_seconds,5)
	$(call print_info,Deleting secret glitchtip-secrets...)
	-@$(KUBECTL) -n $(GLITCHTIP_NAMESPACE) delete secret glitchtip-secrets || true
	$(call print_success,Secret deleted!)

.PHONY: glitchtip-get-secret
glitchtip-get-secret:
	@echo ""
	@echo "$(COLOR_BOLD)=== GlitchTip Secret Info ===$(COLOR_RESET)"
	@$(KUBECTL) -n $(GLITCHTIP_NAMESPACE) get secret glitchtip-secrets >/dev/null 2>&1 && \
		($(call print_success,Secret glitchtip-secrets exists) && \
		 echo "$(COLOR_YELLOW)Secret keys:$(COLOR_RESET)" && \
		 echo "$(COLOR_YELLOW)Secret keys:$(COLOR_RESET)" && \
		 $(call get_secret_keys,$(GLITCHTIP_NAMESPACE),glitchtip-secrets)) || \
		($(call print_warning,Secret glitchtip-secrets not found))
	@echo ""

.PHONY: glitchtip-install
glitchtip-install: install-namespaces glitchtip-check-postgres
	@echo ""
	@echo "$(COLOR_YELLOW)Note:$(COLOR_RESET) Make sure secrets are created:"
	@echo "  make glitchtip-create-secret"
	@echo ""
	@$(KUBECTL) -n $(GLITCHTIP_NAMESPACE) get secret glitchtip-secrets || \
		($(call print_warning,GlitchTip secrets not found!) && \
		 echo "$(COLOR_YELLOW)Please create secrets first:$(COLOR_RESET)" && \
		 echo "  make glitchtip-create-secret" && \
		 exit 1)
	$(call print_info,Applying GlitchTip resource policies...)
	@$(KUBECTL) apply -f glitchtip/manifests/limitrange.yaml
	@$(KUBECTL) apply -f glitchtip/manifests/resourcequota.yaml
	$(call print_info,Creating StorageClass for GlitchTip...)
	@$(KUBECTL) apply -f glitchtip/manifests/storageclass.yaml
	$(call print_info,Applying GlitchTip Ingress resources...)
	@$(KUBECTL) apply -f glitchtip/manifests/ingress.yaml
	$(call print_info,Applying GlitchTip ServiceMonitor for Prometheus...)
	@$(KUBECTL) apply -f monitoring/manifests/monitors/glitchtip-servicemonitor.yaml || \
		($(call print_warning,ServiceMonitor not found, skipping...) && true)
	$(call print_info,Installing GlitchTip via helmfile...)
	$(call run_helmfile,glitchtip/helmfile.yaml,sync)
	$(call print_info,Waiting for GlitchTip to be ready...)
	$(call sleep_seconds,30)
	@$(KUBECTL) -n $(GLITCHTIP_NAMESPACE) wait --for=condition=ready pod -l app.kubernetes.io/component=web --timeout=10m || true
	$(call print_success,GlitchTip installed!)
	@echo ""
	@echo "$(COLOR_YELLOW)Note:$(COLOR_RESET) GlitchTip may take 2-5 minutes to fully start"
	@echo "Monitor with: make glitchtip-status"

.PHONY: glitchtip-update
glitchtip-update:
	$(call print_info,Updating GlitchTip resource policies...)
	@$(KUBECTL) apply -f glitchtip/manifests/limitrange.yaml
	@$(KUBECTL) apply -f glitchtip/manifests/resourcequota.yaml
	$(call print_info,Updating GlitchTip Ingress resources...)
	@$(KUBECTL) apply -f glitchtip/manifests/ingress.yaml
	$(call print_info,Updating GlitchTip ServiceMonitor for Prometheus...)
	@$(KUBECTL) apply -f monitoring/manifests/monitors/glitchtip-servicemonitor.yaml || \
		($(call print_warning,ServiceMonitor not found, skipping...) && true)
	$(call print_info,Updating GlitchTip with new values via helmfile...)
	$(call run_helmfile,glitchtip/helmfile.yaml,sync)
	$(call print_info,Waiting for GlitchTip to be ready...)
	$(call sleep_seconds,30)
	@$(KUBECTL) -n $(GLITCHTIP_NAMESPACE) wait --for=condition=ready pod -l app.kubernetes.io/component=web --timeout=10m || true
	$(call print_success,GlitchTip updated!)
	@echo ""
	@echo "$(COLOR_YELLOW)Note:$(COLOR_RESET) GlitchTip pods will restart with new configuration"

.PHONY: glitchtip-uninstall
glitchtip-uninstall:
	$(call print_warning,This will uninstall GlitchTip!)
	@echo "$(COLOR_YELLOW)Note:$(COLOR_RESET) Data in PostgreSQL will NOT be deleted."
	@echo "Press Ctrl+C to cancel, or wait 10 seconds to continue..."
	$(call sleep_seconds,10)
	$(call print_info,Uninstalling GlitchTip...)
	$(call run_helmfile,glitchtip/helmfile.yaml,destroy) || true
	$(call print_success,GlitchTip uninstalled. PostgreSQL data is preserved.)

.PHONY: glitchtip-status
glitchtip-status:
	@echo ""
	@echo "$(COLOR_BOLD)=== GlitchTip Status ===$(COLOR_RESET)"
	@$(KUBECTL) -n $(GLITCHTIP_NAMESPACE) get pods -o wide
	@echo ""
	@echo "$(COLOR_BOLD)=== GlitchTip Services ===$(COLOR_RESET)"
	@$(KUBECTL) -n $(GLITCHTIP_NAMESPACE) get svc
	@echo ""
	@echo "$(COLOR_BOLD)=== GlitchTip Pod Logs (last 20 lines) ===$(COLOR_RESET)"
	@$(KUBECTL) -n $(GLITCHTIP_NAMESPACE) logs -l app.kubernetes.io/component=web --tail=20 2>&1 || \
		echo "No logs available"
	@echo ""
	@echo "$(COLOR_BOLD)=== Flower Status ===$(COLOR_RESET)"
	@$(KUBECTL) -n $(GLITCHTIP_NAMESPACE) get pods,svc -l app.kubernetes.io/component=flower || \
		echo "Flower not found"
