#!/bin/bash
# =============================================================================
# Phase 7: Deploy Optional Services - Fixed Version
# =============================================================================
# This script deploys the optional services for production:
# 1. CoreDNS configuration with DNS-over-TLS for DNSSEC validation
# 2. Mailu Email Server
# 3. SigNoz Monitoring
#
# DNS Architecture:
# - CoreDNS uses DNS-over-TLS with Cloudflare (1.1.1.1) for DNSSEC validation
# - Mailu uses CoreDNS for DNS resolution (internal K8s + external DNSSEC)
# =============================================================================

set -e

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

NAMESPACE="bakery-ia"
DOMAIN="bakewise.ai"

print_step() {
    echo -e "\n${BLUE}==>${NC} ${GREEN}$1${NC}"
}

print_error() {
    echo -e "${RED}ERROR:${NC} $1"
}

print_success() {
    echo -e "${GREEN}✓${NC} $1"
}

# =============================================================================
# Step 7.1: Configure CoreDNS with DNS-over-TLS for DNSSEC
# =============================================================================
print_step "Step 7.1: Configuring CoreDNS with DNS-over-TLS for DNSSEC validation..."

# Check if CoreDNS is already configured with DNS-over-TLS
CURRENT_FORWARD=$(kubectl get configmap coredns -n kube-system -o jsonpath='{.data.Corefile}' 2>/dev/null | grep -o 'tls://1.1.1.1' || echo "")

if [ -z "$CURRENT_FORWARD" ]; then
    echo "Updating CoreDNS to use DNS-over-TLS with Cloudflare..."

    # Create a temporary file with the CoreDNS configuration
    TEMP_COREFILE=$(mktemp)
    cat > "$TEMP_COREFILE" <<EOF
.:53 {
    errors
    health {
       lameduck 5s
    }
    ready
    kubernetes cluster.local in-addr.arpa ip6.arpa {
       pods insecure
       fallthrough in-addr.arpa ip6.arpa
       ttl 30
    }
    prometheus :9153
    forward . tls://1.1.1.1 tls://1.0.0.1 {
       tls_servername cloudflare-dns.com
       health_check 5s
    }
    cache 30 {
       disable success cluster.local
       disable denial cluster.local
    }
    loop
    reload
    loadbalance
}
EOF

    # Apply the configuration
    kubectl patch configmap coredns -n kube-system --type merge -p "{
      \"data\": {
        \"Corefile\": \"$(cat "$TEMP_COREFILE" | sed 's/\\/\\\\/g' | sed ':a;N;$!ba;s/\n/\\\\n/g')\"
      }
    }"

    rm -f "$TEMP_COREFILE"

    # Restart CoreDNS
    kubectl rollout restart deployment coredns -n kube-system
    kubectl rollout status deployment coredns -n kube-system --timeout=60s

    print_success "CoreDNS configured with DNS-over-TLS"
else
    print_success "CoreDNS already configured with DNS-over-TLS"
fi

# Get CoreDNS service IP
COREDNS_IP=$(kubectl get svc kube-dns -n kube-system -o jsonpath='{.spec.clusterIP}')
echo "CoreDNS service IP: $COREDNS_IP"

# =============================================================================
# Step 7.2: Deploy Mailu Email Server
# =============================================================================
print_step "Step 7.2: Deploying Mailu Email Server..."

# Add Mailu Helm repository
helm repo add mailu https://mailu.github.io/helm-charts 2>/dev/null || true
helm repo update mailu

# Deploy Mailu with CoreDNS configuration
helm upgrade --install mailu mailu/mailu \
    -n "$NAMESPACE" \
    -f infrastructure/platform/mail/mailu-helm/values.yaml \
    -f infrastructure/platform/mail/mailu-helm/prod/values.yaml \
    --set global.custom_dns_servers="$COREDNS_IP" \
    --timeout 10m

print_success "Mailu Helm release deployed"

# Wait for Mailu pods to be ready
echo "Waiting for Mailu pods to be ready (this may take 5-10 minutes)..."
kubectl wait --for=condition=ready pod -l app.kubernetes.io/component=admin -n "$NAMESPACE" --timeout=300s || {
    print_error "Admin pod failed to start. Checking logs..."
    kubectl logs -n "$NAMESPACE" -l app.kubernetes.io/component=admin --tail=50
    exit 1
}

print_success "Mailu deployment completed"

# =============================================================================
# Step 7.3: Deploy SigNoz Monitoring
# =============================================================================
print_step "Step 7.3: Deploying SigNoz Monitoring..."

# Add SigNoz Helm repository
helm repo add signoz https://charts.signoz.io 2>/dev/null || true
helm repo update

# Install SigNoz
helm install signoz signoz/signoz \
  -n "$NAMESPACE" \
  -f infrastructure/monitoring/signoz/signoz-values-prod.yaml \
  --set global.storageClass="microk8s-hostpath" \
  --set clickhouse.persistence.enabled=true \
  --set clickhouse.persistence.size=50Gi \
  --timeout 15m

# Wait for SigNoz to be ready
kubectl wait --for=condition=available --timeout=600s deployment/signoz-frontend -n "$NAMESPACE"

print_success "SigNoz deployment completed"

# =============================================================================
# Summary
# =============================================================================
echo ""
echo "=============================================="
echo -e "${GREEN}Phase 7 Deployment Complete!${NC}"
echo "=============================================="
echo ""
echo "Deployed Services:"
echo "  ✓ CoreDNS (configured with DNS-over-TLS for DNSSEC)"
echo "  ✓ Mailu Email Server (using CoreDNS IP: $COREDNS_IP)"
echo "  ✓ SigNoz Monitoring"
echo ""
echo "Next Steps:"
echo "  1. Configure DNS records for mail.$DOMAIN"
echo "  2. Set up Mailgun relay credentials"
echo "  3. Configure Ingress for monitoring.$DOMAIN"
echo "  4. Verify all services are accessible"
echo ""
