#!/bin/bash

# HGZero Backend Services Kubernetes Undeployment Script

set -e

# Color codes for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# Configuration
NAMESPACE="hgzero"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

echo -e "${YELLOW}======================================${NC}"
echo -e "${YELLOW}HGZero Backend Services Undeployment${NC}"
echo -e "${YELLOW}======================================${NC}"

# Check if kubectl is installed
if ! command -v kubectl &> /dev/null; then
    echo -e "${RED}Error: kubectl is not installed${NC}"
    exit 1
fi

# Verify connection to cluster
echo -e "${YELLOW}Verifying connection to Kubernetes cluster...${NC}"
if ! kubectl cluster-info &> /dev/null; then
    echo -e "${RED}Error: Cannot connect to Kubernetes cluster${NC}"
    exit 1
fi

# Check if namespace exists
if ! kubectl get namespace ${NAMESPACE} &> /dev/null; then
    echo -e "${YELLOW}Namespace '${NAMESPACE}' does not exist. Nothing to undeploy.${NC}"
    exit 0
fi

echo -e "${YELLOW}This will delete all services in namespace '${NAMESPACE}'${NC}"
read -p "Are you sure you want to continue? (y/N): " -n 1 -r
echo
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
    echo -e "${YELLOW}Undeployment cancelled${NC}"
    exit 0
fi

# Delete services
echo -e "${YELLOW}Deleting Meeting Service...${NC}"
kubectl delete -f ${SCRIPT_DIR}/meeting-service.yaml --ignore-not-found=true
echo -e "${GREEN}✓ Meeting Service deleted${NC}"

echo -e "${YELLOW}Deleting Notification Service...${NC}"
kubectl delete -f ${SCRIPT_DIR}/notification-service.yaml --ignore-not-found=true
echo -e "${GREEN}✓ Notification Service deleted${NC}"

echo -e "${YELLOW}Deleting User Service...${NC}"
kubectl delete -f ${SCRIPT_DIR}/user-service.yaml --ignore-not-found=true
echo -e "${GREEN}✓ User Service deleted${NC}"

# Delete ConfigMaps
echo -e "${YELLOW}Deleting ConfigMaps...${NC}"
kubectl delete -f ${SCRIPT_DIR}/configmap.yaml --ignore-not-found=true
echo -e "${GREEN}✓ ConfigMaps deleted${NC}"

# Ask about secrets deletion
echo ""
echo -e "${YELLOW}Do you want to delete secrets as well?${NC}"
echo -e "${RED}Warning: This will delete all database and Azure credentials${NC}"
read -p "Delete secrets? (y/N): " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
    kubectl delete secret db-secret azure-secret mail-secret -n ${NAMESPACE} --ignore-not-found=true
    echo -e "${GREEN}✓ Secrets deleted${NC}"
fi

# Ask about namespace deletion
echo ""
echo -e "${YELLOW}Do you want to delete the namespace '${NAMESPACE}'?${NC}"
read -p "Delete namespace? (y/N): " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
    kubectl delete namespace ${NAMESPACE}
    echo -e "${GREEN}✓ Namespace deleted${NC}"
fi

echo -e "${GREEN}======================================${NC}"
echo -e "${GREEN}Undeployment Completed${NC}"
echo -e "${GREEN}======================================${NC}"
