#!/usr/bin/env bash

# Apply all database security changes to Kubernetes cluster

set -e

NAMESPACE="bakery-ia"

echo "======================================"
echo "Bakery IA Database Security Deployment"
echo "======================================"
echo ""
echo "This script will apply all security changes to the cluster:"
echo "  1. Updated passwords"
echo "  2. TLS certificates for PostgreSQL and Redis"
echo "  3. Updated database deployments with TLS and PVCs"
echo "  4. PostgreSQL logging configuration"
echo "  5. pgcrypto extension"
echo ""
read -p "Press Enter to continue or Ctrl+C to cancel..."
echo ""

# ===== 1. Apply Secrets =====
echo "Step 1: Applying updated secrets..."
kubectl apply -f infrastructure/kubernetes/base/secrets.yaml
kubectl apply -f infrastructure/kubernetes/base/secrets/postgres-tls-secret.yaml
kubectl apply -f infrastructure/kubernetes/base/secrets/redis-tls-secret.yaml
echo "✓ Secrets applied"
echo ""

# ===== 2. Apply ConfigMaps =====
echo "Step 2: Applying ConfigMaps..."
kubectl apply -f infrastructure/kubernetes/base/configs/postgres-init-config.yaml
kubectl apply -f infrastructure/kubernetes/base/configmaps/postgres-logging-config.yaml
echo "✓ ConfigMaps applied"
echo ""

# ===== 3. Apply Database Deployments =====
echo "Step 3: Applying database deployments..."
kubectl apply -f infrastructure/kubernetes/base/components/databases/
echo "✓ Database deployments applied"
echo ""

# ===== 4. Wait for Rollout =====
echo "Step 4: Waiting for database pods to be ready..."

DBS=(
  "auth-db"
  "tenant-db"
  "training-db"
  "forecasting-db"
  "sales-db"
  "external-db"
  "notification-db"
  "inventory-db"
  "recipes-db"
  "suppliers-db"
  "pos-db"
  "orders-db"
  "production-db"
  "alert-processor-db"
  "redis"
)

for db in "${DBS[@]}"; do
  echo "  Waiting for $db..."
  kubectl rollout status deployment/$db -n $NAMESPACE --timeout=5m || echo "  ⚠️  Warning: $db rollout may have issues"
done

echo "✓ All deployments rolled out"
echo ""

# ===== 5. Verify PVCs =====
echo "Step 5: Verifying PersistentVolumeClaims..."
kubectl get pvc -n $NAMESPACE
echo ""

# ===== 6. Test Database Connections =====
echo "Step 6: Testing database connectivity..."

# Test PostgreSQL with TLS
echo "  Testing PostgreSQL (auth-db) with TLS..."
AUTH_POD=$(kubectl get pods -n $NAMESPACE -l app.kubernetes.io/name=auth-db -o jsonpath='{.items[0].metadata.name}')
if [ -n "$AUTH_POD" ]; then
  kubectl exec -n $NAMESPACE "$AUTH_POD" -- \
    sh -c 'psql -U $POSTGRES_USER -d $POSTGRES_DB -c "SELECT version();"' > /dev/null 2>&1 && \
    echo "  ✓ PostgreSQL connection successful" || \
    echo "  ⚠️  PostgreSQL connection test failed"
else
  echo "  ⚠️  auth-db pod not found"
fi

# Test Redis with TLS
echo "  Testing Redis with TLS..."
REDIS_POD=$(kubectl get pods -n $NAMESPACE -l app.kubernetes.io/name=redis -o jsonpath='{.items[0].metadata.name}')
if [ -n "$REDIS_POD" ]; then
  kubectl exec -n $NAMESPACE "$REDIS_POD" -- \
    redis-cli -a $(kubectl get secret redis-secrets -n $NAMESPACE -o jsonpath='{.data.REDIS_PASSWORD}' | base64 -d) \
    --tls --cert /tls/redis-cert.pem --key /tls/redis-key.pem --cacert /tls/ca-cert.pem \
    PING > /dev/null 2>&1 && \
    echo "  ✓ Redis TLS connection successful" || \
    echo "  ⚠️  Redis TLS connection test failed (may need to restart services)"
else
  echo "  ⚠️  Redis pod not found"
fi

echo ""

# ===== 7. Verify TLS Certificates =====
echo "Step 7: Verifying TLS certificates are mounted..."

echo "  Checking PostgreSQL TLS certs..."
if [ -n "$AUTH_POD" ]; then
  kubectl exec -n $NAMESPACE "$AUTH_POD" -- ls -la /tls/ 2>/dev/null && \
    echo "  ✓ PostgreSQL TLS certificates mounted" || \
    echo "  ⚠️  PostgreSQL TLS certificates not found"
fi

echo "  Checking Redis TLS certs..."
if [ -n "$REDIS_POD" ]; then
  kubectl exec -n $NAMESPACE "$REDIS_POD" -- ls -la /tls/ 2>/dev/null && \
    echo "  ✓ Redis TLS certificates mounted" || \
    echo "  ⚠️  Redis TLS certificates not found"
fi

echo ""

# ===== 8. Display Summary =====
echo "======================================"
echo "Deployment Summary"
echo "======================================"
echo ""
echo "Database Pods:"
kubectl get pods -n $NAMESPACE -l app.kubernetes.io/component=database
echo ""
echo "PersistentVolumeClaims:"
kubectl get pvc -n $NAMESPACE | grep -E "NAME|db-pvc"
echo ""
echo "Secrets:"
kubectl get secrets -n $NAMESPACE | grep -E "NAME|database-secrets|redis-secrets|postgres-tls|redis-tls"
echo ""

echo "======================================"
echo "✓ Security Deployment Complete!"
echo "======================================"
echo ""
echo "Security improvements applied:"
echo "  ✅ Strong 32-character passwords for all databases"
echo "  ✅ TLS encryption for PostgreSQL connections"
echo "  ✅ TLS encryption for Redis connections"
echo "  ✅ Persistent storage (PVCs) for all databases"
echo "  ✅ pgcrypto extension enabled for column-level encryption"
echo "  ✅ PostgreSQL audit logging configured"
echo ""
echo "Next steps:"
echo "  1. Restart all services to pick up new database URLs with TLS"
echo "  2. Monitor logs for any connection issues"
echo "  3. Test application functionality end-to-end"
echo "  4. Review PostgreSQL logs: kubectl logs -n $NAMESPACE <db-pod>"
echo ""
echo "To create encrypted backups, run:"
echo "  ./scripts/encrypted-backup.sh"
echo ""
echo "To enable Kubernetes secrets encryption (requires cluster recreate):"
echo "  kind delete cluster --name bakery-ia-local"
echo "  kind create cluster --config kind-config.yaml"
echo "  kubectl apply -f infrastructure/kubernetes/base/namespace.yaml"
echo "  ./scripts/apply-security-changes.sh"
