#!/bin/bash
# Integrate existing Azure CDN configuration from azure-cdn-config.env
# Updates .env file with CDN values if they exist

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
CDN_CONFIG="$PROJECT_ROOT/azure-cdn-config.env"
ENV_FILE="$PROJECT_ROOT/.env"

echo "🔄 Integrating Azure CDN configuration..."

if [ -f "$CDN_CONFIG" ]; then
  echo "Found existing CDN configuration: $CDN_CONFIG"
  
  # Load CDN config
  set -a
  source "$CDN_CONFIG"
  set +a
  
  # Update .env file with CDN values if not already set
  if [ -f "$ENV_FILE" ]; then
    # Check if CDN values are already in .env
    if ! grep -q "AZURE_STORAGE_ACCOUNT=" "$ENV_FILE" 2>/dev/null; then
      echo "Adding CDN configuration to .env file..."
      cat >> "$ENV_FILE" << EOF

# Azure CDN Configuration (from azure-cdn-config.env)
AZURE_STORAGE_ACCOUNT=${AZURE_STORAGE_ACCOUNT:-}
AZURE_STORAGE_KEY=${AZURE_STORAGE_KEY:-}
AZURE_STORAGE_CONTAINER=${AZURE_STORAGE_CONTAINER:-images}
AZURE_RESOURCE_GROUP=${AZURE_RESOURCE_GROUP:-}
AZURE_CDN_PROFILE=${AZURE_CDN_PROFILE:-}
AZURE_CDN_ENDPOINT=${AZURE_CDN_ENDPOINT:-}
CDN_BASE_URL=${CDN_BASE_URL:-}
CDN_BASE_URL_BLOB=${CDN_BASE_URL_BLOB:-}
CDN_BASE_URL_CDN=${CDN_BASE_URL_CDN:-}
EOF
      echo "✅ CDN configuration added to .env"
    else
      echo "ℹ️  CDN configuration already exists in .env"
    fi
  else
    echo "⚠️  .env file not found. Creating from CDN config..."
    cp "$CDN_CONFIG" "$ENV_FILE"
    echo "✅ Created .env from CDN config"
  fi
  
  # Export for Terraform
  export TF_VAR_storage_account_name="${AZURE_STORAGE_ACCOUNT}"
  export TF_VAR_cdn_profile_name="${AZURE_CDN_PROFILE}"
  export TF_VAR_cdn_endpoint_name="${AZURE_CDN_ENDPOINT}"
  
  echo ""
  echo "CDN Configuration:"
  echo "  Storage Account: ${AZURE_STORAGE_ACCOUNT}"
  echo "  CDN Profile: ${AZURE_CDN_PROFILE}"
  echo "  CDN Endpoint: ${AZURE_CDN_ENDPOINT}"
  echo "  Base URL: ${CDN_BASE_URL}"
else
  echo "ℹ️  No existing CDN configuration found at: $CDN_CONFIG"
  echo "   CDN will be created by Terraform if needed"
fi

echo ""
echo "✅ CDN integration complete!"

