#!/bin/bash

# HGZero Backend Services Kubernetes Deployment Script
# Azure Container Registry: acrdigitalgarage02
# Azure Kubernetes Service: aks-digitalgarage-02
# Namespace: hgzero

set -e

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

# Configuration
ACR_NAME="acrdigitalgarage02"
AKS_NAME="aks-digitalgarage-02"
RESOURCE_GROUP="rg-digitalgarage-02"
NAMESPACE="hgzero"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

echo -e "${GREEN}======================================${NC}"
echo -e "${GREEN}HGZero Backend Services Deployment${NC}"
echo -e "${GREEN}======================================${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

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

# Login to Azure (if not already logged in)
echo -e "${YELLOW}Checking Azure login status...${NC}"
if ! az account show &> /dev/null; then
    echo -e "${YELLOW}Please login to Azure...${NC}"
    az login
fi

# Get AKS credentials
echo -e "${YELLOW}Getting AKS credentials...${NC}"
az aks get-credentials --resource-group ${RESOURCE_GROUP} --name ${AKS_NAME} --overwrite-existing

# 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
echo -e "${GREEN}✓ Successfully connected to ${AKS_NAME}${NC}"

# Create namespace if it doesn't exist
echo -e "${YELLOW}Creating namespace '${NAMESPACE}'...${NC}"
kubectl apply -f ${SCRIPT_DIR}/namespace.yaml
echo -e "${GREEN}✓ Namespace created/verified${NC}"

# Apply ConfigMaps
echo -e "${YELLOW}Applying ConfigMaps...${NC}"
kubectl apply -f ${SCRIPT_DIR}/configmap.yaml
echo -e "${GREEN}✓ ConfigMaps applied${NC}"

# Check if secrets exist
echo -e "${YELLOW}Checking for secrets...${NC}"
if ! kubectl get secret db-secret -n ${NAMESPACE} &> /dev/null || \
   ! kubectl get secret azure-secret -n ${NAMESPACE} &> /dev/null || \
   ! kubectl get secret mail-secret -n ${NAMESPACE} &> /dev/null; then
    echo -e "${RED}Warning: One or more secrets are missing!${NC}"
    echo -e "${YELLOW}Please create secrets using secret-template.yaml as reference${NC}"
    echo -e "${YELLOW}Example:${NC}"
    echo -e "  kubectl create secret generic db-secret -n ${NAMESPACE} \\"
    echo -e "    --from-literal=host=<DB_HOST> \\"
    echo -e "    --from-literal=username=<DB_USERNAME> \\"
    echo -e "    --from-literal=password=<DB_PASSWORD>"
    echo ""
    read -p "Do you want to continue without secrets? (y/N): " -n 1 -r
    echo
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        echo -e "${RED}Deployment cancelled${NC}"
        exit 1
    fi
fi

# Configure ACR integration
echo -e "${YELLOW}Configuring ACR integration...${NC}"
az aks update -n ${AKS_NAME} -g ${RESOURCE_GROUP} --attach-acr ${ACR_NAME}
echo -e "${GREEN}✓ ACR integration configured${NC}"

# Deploy services
echo -e "${YELLOW}Deploying User Service...${NC}"
kubectl apply -f ${SCRIPT_DIR}/user-service.yaml
echo -e "${GREEN}✓ User Service deployed${NC}"

echo -e "${YELLOW}Deploying Notification Service...${NC}"
kubectl apply -f ${SCRIPT_DIR}/notification-service.yaml
echo -e "${GREEN}✓ Notification Service deployed${NC}"

echo -e "${YELLOW}Deploying Meeting Service...${NC}"
kubectl apply -f ${SCRIPT_DIR}/meeting-service.yaml
echo -e "${GREEN}✓ Meeting Service deployed${NC}"

# Wait for deployments to be ready
echo -e "${YELLOW}Waiting for deployments to be ready...${NC}"
kubectl wait --for=condition=available --timeout=300s \
    deployment/user-service \
    deployment/notification-service \
    deployment/meeting-service \
    -n ${NAMESPACE}

# Show deployment status
echo -e "${GREEN}======================================${NC}"
echo -e "${GREEN}Deployment Status${NC}"
echo -e "${GREEN}======================================${NC}"
kubectl get deployments -n ${NAMESPACE}
echo ""
kubectl get pods -n ${NAMESPACE}
echo ""
kubectl get services -n ${NAMESPACE}

echo -e "${GREEN}======================================${NC}"
echo -e "${GREEN}Deployment Completed Successfully!${NC}"
echo -e "${GREEN}======================================${NC}"
echo ""
echo -e "${YELLOW}Useful commands:${NC}"
echo -e "  View logs: kubectl logs -f deployment/<service-name> -n ${NAMESPACE}"
echo -e "  View pods: kubectl get pods -n ${NAMESPACE}"
echo -e "  Describe pod: kubectl describe pod <pod-name> -n ${NAMESPACE}"
echo -e "  Port forward: kubectl port-forward svc/<service-name> <local-port>:<service-port> -n ${NAMESPACE}"
