#!/bin/bash
# Update Kubernetes secrets from Azure Key Vault
# Uses values from .env file to configure External Secrets

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"

echo "🔄 Updating Kubernetes secrets configuration from .env..."

# Load environment
source "$SCRIPT_DIR/azure-validate-env.sh"

# Get Key Vault URI from Terraform output if available
cd "$PROJECT_ROOT/infra/terraform"
if terraform output -json key_vault_uri &> /dev/null; then
  KEY_VAULT_URI=$(terraform output -raw key_vault_uri)
  echo "Found Key Vault URI from Terraform: $KEY_VAULT_URI"
else
  # Construct from known values
  KEY_VAULT_NAME="${TF_VAR_key_vault_name:-the-order-kv-${TF_VAR_environment:-dev}}"
  KEY_VAULT_URI="https://${KEY_VAULT_NAME}.vault.azure.net/"
  echo "Using constructed Key Vault URI: $KEY_VAULT_URI"
fi

# Update External Secrets configuration
EXTERNAL_SECRETS_FILE="$PROJECT_ROOT/infra/k8s/base/external-secrets.yaml"

# Use sed or create a template update
if [ -f "$EXTERNAL_SECRETS_FILE" ]; then
  # Create updated version
  sed -i.bak "s|tenantId: \"\"|tenantId: \"${ARM_TENANT_ID}\"|g" "$EXTERNAL_SECRETS_FILE"
  sed -i.bak "s|vaultUrl: \"\"|vaultUrl: \"${KEY_VAULT_URI}\"|g" "$EXTERNAL_SECRETS_FILE"
  rm -f "${EXTERNAL_SECRETS_FILE}.bak"
  echo "✅ Updated External Secrets configuration"
else
  echo "⚠️  External Secrets file not found: $EXTERNAL_SECRETS_FILE"
fi

# Update Azure ConfigMap
CONFIGMAP_FILE="$PROJECT_ROOT/infra/k8s/base/configmap-azure.yaml"

if [ -f "$CONFIGMAP_FILE" ]; then
  # Update with actual values (non-sensitive)
  sed -i.bak "s|AZURE_REGION: \".*\"|AZURE_REGION: \"${ARM_LOCATION:-westeurope}\"|g" "$CONFIGMAP_FILE"
  sed -i.bak "s|AKS_RESOURCE_GROUP: \".*\"|AKS_RESOURCE_GROUP: \"${TF_VAR_resource_group_name}\"|g" "$CONFIGMAP_FILE"
  rm -f "${CONFIGMAP_FILE}.bak"
  echo "✅ Updated Azure ConfigMap"
else
  echo "⚠️  ConfigMap file not found: $CONFIGMAP_FILE"
fi

echo ""
echo "✅ Kubernetes secrets configuration updated!"
echo ""
echo "Next steps:"
echo "  1. Review updated files:"
echo "     - $EXTERNAL_SECRETS_FILE"
echo "     - $CONFIGMAP_FILE"
echo "  2. Apply to Kubernetes:"
echo "     kubectl apply -f $EXTERNAL_SECRETS_FILE"
echo "     kubectl apply -f $CONFIGMAP_FILE"

