#!/usr/bin/env bash

# Grant Key Vault permissions using the provided Azure CLI method
# Handles both access policies and RBAC-enabled vaults

set -e

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

# Your AAD object ID
OBJECT_ID="5c40d456-49d2-4f2a-b35c-66255ca33b04"

# Email for logging
USER_EMAIL="admin@absoluterealms.org"

# Subscription ID
SUBSCRIPTION_ID="fc08d829-4f14-413d-ab27-ce024425db0b"

echo "╔════════════════════════════════════════════════════════════════╗"
echo "║     GRANTING KEY VAULT PERMISSIONS                                ║"
echo "╚════════════════════════════════════════════════════════════════╝"

echo "User: $USER_EMAIL"
echo "Object ID: $OBJECT_ID"
echo "Subscription: $SUBSCRIPTION_ID"

# Set subscription
az account set --subscription "$SUBSCRIPTION_ID"

echo "Processing subscription: $SUBSCRIPTION_ID"

SUCCESS_COUNT=0
FAILED_COUNT=0
RBAC_COUNT=0
POLICY_COUNT=0

# Get all Key Vault names in this subscription
for KV in $(az keyvault list --query "[].name" -o tsv 2>/dev/null); do
  echo "  -> Updating Key Vault: $KV"
  
  # Get resource group
  KV_RG=$(az keyvault show --name "$KV" --query "resourceGroup" -o tsv 2>/dev/null)
  
  if [ -z "$KV_RG" ]; then
    echo "    ❌ Could not get resource group"
    ((FAILED_COUNT++))
    continue
  fi
  
  # Check if RBAC-enabled
  IS_RBAC=$(az keyvault show --name "$KV" --query "properties.enableRbacAuthorization" -o tsv 2>/dev/null)
  
  if [ "$IS_RBAC" = "true" ]; then
    # Use RBAC role assignment
    echo "    Using RBAC (Key Vault Secrets Officer)"
    az role assignment create \
      --role "Key Vault Secrets Officer" \
      --assignee "$OBJECT_ID" \
      --scope "/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$KV_RG/providers/Microsoft.KeyVault/vaults/$KV" \
      > /dev/null 2>&1
    
    if [ $? -eq 0 ]; then
      echo "    ✅ RBAC role assigned"
      ((SUCCESS_COUNT++))
      ((RBAC_COUNT++))
    else
      echo "    ❌ Failed to assign RBAC role"
      ((FAILED_COUNT++))
    fi
  else
    # Use access policy
    echo "    Using Access Policy"
    az keyvault set-policy \
      --name "$KV" \
      --object-id "$OBJECT_ID" \
      --secret-permissions get list set delete backup restore recover purge \
      > /dev/null 2>&1
    
    if [ $? -eq 0 ]; then
      echo "    ✅ Access policy updated"
      ((SUCCESS_COUNT++))
      ((POLICY_COUNT++))
    else
      echo "    ❌ Failed to update access policy"
      ((FAILED_COUNT++))
    fi
  fi
  
done

echo "======================================================================"
echo "📊 SUMMARY"
echo "======================================================================"
echo "Total Key Vaults processed: $((SUCCESS_COUNT + FAILED_COUNT))"
echo "✅ Success: $SUCCESS_COUNT"
echo "   - Access Policy: $POLICY_COUNT"
echo "   - RBAC: $RBAC_COUNT"
echo "❌ Failed: $FAILED_COUNT"

if [ $FAILED_COUNT -eq 0 ]; then
  echo "✅ All permissions granted successfully"
  exit 0
else
  echo "⚠️  Some permissions failed - check errors above"
  exit 1
fi

