#!/usr/bin/env bash

set -e

# Setup Azure Key Vault for key storage
# This script creates an Azure Key Vault and sets up access policies
#
# NOTE: For production, consider using the enhanced Key Vault module with RBAC
# See terraform/modules/keyvault-enhanced/ for Well-Architected Framework implementation
# See docs/AZURE_WELL_ARCHITECTED_REVIEW.md for details

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
source "$SCRIPT_DIR/../lib/init.sh"
SCRIPT_NAME="azure-keyvault-setup.sh"
SCRIPT_DESC="Set up Azure Key Vaults with RBAC/access policies and AKS managed identity access"
SCRIPT_USAGE="${SCRIPT_NAME} [--region <name>] [--dry-run] [--help]"
SCRIPT_OPTIONS="--region <name>   Limit setup to a specific region\n--dry-run         Print actions without executing\n--help            Show help"
SCRIPT_REQUIREMENTS="Azure CLI (ensure_azure_cli), permissions to manage Key Vaults"
handle_help "${1:-}"

# Initialize
SUBSCRIPTION_ID="$(get_subscription_id)"
ensure_azure_cli || exit 1
set_subscription "$SUBSCRIPTION_ID" || true

# Configuration
ENVIRONMENT="${ENVIRONMENT:-prod}"
RESOURCE_GROUP="${RESOURCE_GROUP:-rg-${ENVIRONMENT}-security-001}"
KEY_VAULT_NAME="${KEY_VAULT_NAME:-kv-${ENVIRONMENT}-secrets-001}"
LOCATION="${LOCATION:-westeurope}"
USE_RBAC="${USE_RBAC:-false}"  # Set to true to use RBAC instead of access policies

log_section "SETTING UP AZURE KEY VAULT"
log_info "Vault: $KEY_VAULT_NAME"

# CLI and login ensured by library above

# Create resource group if it doesn't exist
az group create --name "$RESOURCE_GROUP" --location "$LOCATION" || true

# Create Key Vault
log_info "Creating Key Vault: $KEY_VAULT_NAME in resource group: $RESOURCE_GROUP"

az keyvault create \
    --name "$KEY_VAULT_NAME" \
    --resource-group "$RESOURCE_GROUP" \
    --location "$LOCATION" \
    --enable-soft-delete true \
    --enable-purge-protection $([ "$ENVIRONMENT" == "prod" ] && echo "true" || echo "false") \
    --retention-days $([ "$ENVIRONMENT" == "prod" ] && echo "90" || echo "7") \
    --sku standard

# Configure network access (restrict in production)
if [ "$ENVIRONMENT" == "prod" ]; then
    log_info "Configuring network restrictions for production..."
    # Default action: Deny (restrict access)
    az keyvault update \
        --name "$KEY_VAULT_NAME" \
        --resource-group "$RESOURCE_GROUP" \
        --default-action Deny \
        --bypass AzureServices
else
    log_info "Using permissive network access for non-production environment..."
    # Default action: Allow (permissive for dev/test)
    az keyvault update \
        --name "$KEY_VAULT_NAME" \
        --resource-group "$RESOURCE_GROUP" \
        --default-action Allow \
        --bypass AzureServices
fi

# Configure access (RBAC or Access Policies)
if [ "$USE_RBAC" == "true" ]; then
    log_info "Enabling RBAC authorization..."
    az keyvault update \
        --name "$KEY_VAULT_NAME" \
        --resource-group "$RESOURCE_GROUP" \
        --enable-rbac-authorization true
    
    # Get current user object ID
    CURRENT_USER_OBJECT_ID=$(az ad signed-in-user show --query id -o tsv)
    
    # Assign Key Vault Administrator role
    az role assignment create \
        --role "Key Vault Administrator" \
        --assignee "$CURRENT_USER_OBJECT_ID" \
        --scope "/subscriptions/$(az account show --query id -o tsv)/resourceGroups/$RESOURCE_GROUP/providers/Microsoft.KeyVault/vaults/$KEY_VAULT_NAME"
else
    log_info "Using access policies (legacy method)..."
    # Get current user principal
    CURRENT_USER=$(az account show --query user.name -o tsv)
    
    # Set access policy for current user
    az keyvault set-policy \
        --name "$KEY_VAULT_NAME" \
        --upn "$CURRENT_USER" \
        --secret-permissions get list set delete \
        --key-permissions get list create import
fi

# Get AKS managed identity (if AKS exists)
AKS_CLUSTER_NAME="${AKS_CLUSTER_NAME:-defi-oracle-aks}"
AKS_RESOURCE_GROUP="${AKS_RESOURCE_GROUP:-$RESOURCE_GROUP}"

if az aks show --name "$AKS_CLUSTER_NAME" --resource-group "$AKS_RESOURCE_GROUP" &> /dev/null; then
    log_info "Configuring AKS managed identity access..."
    
    # Get AKS node resource group
    NODE_RESOURCE_GROUP=$(az aks show \
        --name "$AKS_CLUSTER_NAME" \
        --resource-group "$AKS_RESOURCE_GROUP" \
        --query nodeResourceGroup -o tsv)
    
    # Get AKS managed identity
    AKS_IDENTITY_ID=$(az aks show \
        --name "$AKS_CLUSTER_NAME" \
        --resource-group "$AKS_RESOURCE_GROUP" \
        --query identity.principalId -o tsv)
    
    if [ -n "$AKS_IDENTITY_ID" ]; then
        az keyvault set-policy \
            --name "$KEY_VAULT_NAME" \
            --object-id "$AKS_IDENTITY_ID" \
            --secret-permissions get list \
            --key-permissions get list
    fi
fi

log_success "Azure Key Vault setup complete!"
echo "Key Vault Name: $KEY_VAULT_NAME"
echo "Resource Group: $RESOURCE_GROUP"
echo "Location: $LOCATION"
echo ""
echo "To store a key:"
echo "  az keyvault secret set --vault-name $KEY_VAULT_NAME --name validator-key-1 --value <key>"
echo ""
echo "To list all secrets:"
echo "  az keyvault secret list --vault-name $KEY_VAULT_NAME"
echo ""
echo "To retrieve a secret:"
echo "  az keyvault secret show --vault-name $KEY_VAULT_NAME --name validator-key-1 --query value -o tsv"

