#!/bin/bash
# Comprehensive Azure quota check for CDN and storage setup
# Checks all quotas needed for credential seal CDN deployment

set -euo pipefail

GREEN='\033[0;32m'
BLUE='\033[0;34m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m'

log_info() { echo -e "${BLUE}[CHECK]${NC} $1"; }
log_success() { echo -e "${GREEN}[✓]${NC} $1"; }
log_warning() { echo -e "${YELLOW}[!]${NC} $1"; }
log_error() { echo -e "${RED}[✗]${NC} $1"; }

# Check if Azure CLI is installed
if ! command -v az &> /dev/null; then
    log_error "Azure CLI is not installed"
    exit 1
fi

# Check if logged in
if ! az account show &> /dev/null; then
    log_error "Not logged in to Azure. Please log in: az login"
    exit 1
fi

SUBSCRIPTION_ID=$(az account show --query id -o tsv)
SUBSCRIPTION_NAME=$(az account show --query name -o tsv)
LOCATION="${AZURE_LOCATION:-westeurope}"

log_info "Azure Quota Check for CDN Setup"
echo "Subscription: ${SUBSCRIPTION_NAME} (${SUBSCRIPTION_ID})"
echo "Location: ${LOCATION}"
echo ""

QUOTA_FILE="azure-cdn-quota-report.txt"
cat > "${QUOTA_FILE}" << EOF
Azure CDN Quota Report
Generated: $(date -u +"%Y-%m-%d %H:%M:%S UTC")
Subscription: ${SUBSCRIPTION_NAME} (${SUBSCRIPTION_ID})
Location: ${LOCATION}

EOF

ISSUES=0
WARNINGS=0

# 1. Storage Account Quota
log_info "1. Storage Account Quota"
STORAGE_QUOTA=$(az storage account show-usage --location "${LOCATION}" -o json 2>/dev/null || echo "{}")
STORAGE_CURRENT=$(echo "${STORAGE_QUOTA}" | jq -r '.currentValue // 0' 2>/dev/null || echo "0")
STORAGE_LIMIT=$(echo "${STORAGE_QUOTA}" | jq -r '.limit // 250' 2>/dev/null || echo "250")

echo "Storage Accounts:" >> "${QUOTA_FILE}"
echo "  Current: ${STORAGE_CURRENT}" >> "${QUOTA_FILE}"
echo "  Limit: ${STORAGE_LIMIT}" >> "${QUOTA_FILE}"
echo "  Available: $((STORAGE_LIMIT - STORAGE_CURRENT))" >> "${QUOTA_FILE}"

if [ "${STORAGE_CURRENT}" -ge "${STORAGE_LIMIT}" ]; then
    log_error "  Quota exceeded: ${STORAGE_CURRENT}/${STORAGE_LIMIT}"
    ((ISSUES++))
elif [ $((STORAGE_LIMIT - STORAGE_CURRENT)) -lt 1 ]; then
    log_warning "  Quota nearly full: ${STORAGE_CURRENT}/${STORAGE_LIMIT}"
    ((WARNINGS++))
else
    log_success "  OK: ${STORAGE_CURRENT}/${STORAGE_LIMIT} (${STORAGE_LIMIT} - ${STORAGE_CURRENT} available)"
fi

# 2. CDN Profile Quota
log_info "2. CDN Profile Quota"
CDN_PROFILES=$(az cdn profile list --query "[].{Name:name}" -o tsv 2>/dev/null | wc -l || echo "0")
CDN_LIMIT=25  # Default Azure CDN limit

echo "" >> "${QUOTA_FILE}"
echo "CDN Profiles:" >> "${QUOTA_FILE}"
echo "  Current: ${CDN_PROFILES}" >> "${QUOTA_FILE}"
echo "  Limit: ${CDN_LIMIT}" >> "${QUOTA_FILE}"
echo "  Available: $((CDN_LIMIT - CDN_PROFILES))" >> "${QUOTA_FILE}"

if [ "${CDN_PROFILES}" -ge "${CDN_LIMIT}" ]; then
    log_error "  Quota exceeded: ${CDN_PROFILES}/${CDN_LIMIT}"
    ((ISSUES++))
elif [ $((CDN_LIMIT - CDN_PROFILES)) -lt 2 ]; then
    log_warning "  Quota nearly full: ${CDN_PROFILES}/${CDN_LIMIT}"
    ((WARNINGS++))
else
    log_success "  OK: ${CDN_PROFILES}/${CDN_LIMIT} ($((CDN_LIMIT - CDN_PROFILES)) available)"
fi

# 3. Resource Group Quota
log_info "3. Resource Group Quota"
RG_COUNT=$(az group list --query "[].{Name:name}" -o tsv 2>/dev/null | wc -l || echo "0")
RG_LIMIT=980  # Default Azure limit

echo "" >> "${QUOTA_FILE}"
echo "Resource Groups:" >> "${QUOTA_FILE}"
echo "  Current: ${RG_COUNT}" >> "${QUOTA_FILE}"
echo "  Limit: ${RG_LIMIT}" >> "${QUOTA_FILE}"
echo "  Available: $((RG_LIMIT - RG_COUNT))" >> "${QUOTA_FILE}"

if [ "${RG_COUNT}" -ge "${RG_LIMIT}" ]; then
    log_error "  Quota exceeded: ${RG_COUNT}/${RG_LIMIT}"
    ((ISSUES++))
else
    log_success "  OK: ${RG_COUNT}/${RG_LIMIT} ($((RG_LIMIT - RG_COUNT)) available)"
fi

# 4. Storage Account Capacity (if we can check)
log_info "4. Storage Account Capacity"
echo "" >> "${QUOTA_FILE}"
echo "Storage Account Capacity:" >> "${QUOTA_FILE}"
echo "  Note: Capacity limits depend on subscription type" >> "${QUOTA_FILE}"
echo "  Standard accounts: Up to 5 PiB per account" >> "${QUOTA_FILE}"
log_success "  OK: Sufficient for credential images (files are small)"

# 5. CDN Endpoint Quota
log_info "5. CDN Endpoint Quota"
CDN_ENDPOINTS=$(az cdn endpoint list --query "[].{Name:name}" -o tsv 2>/dev/null | wc -l)
CDN_ENDPOINTS=${CDN_ENDPOINTS:-0}
CDN_ENDPOINT_LIMIT=25  # Per profile

echo "" >> "${QUOTA_FILE}"
echo "CDN Endpoints:" >> "${QUOTA_FILE}"
echo "  Current: ${CDN_ENDPOINTS}" >> "${QUOTA_FILE}"
echo "  Limit: ${CDN_ENDPOINT_LIMIT} per profile" >> "${QUOTA_FILE}"

if [ "${CDN_ENDPOINTS}" -ge "${CDN_ENDPOINT_LIMIT}" ]; then
    log_warning "  Many endpoints: ${CDN_ENDPOINTS} (limit: ${CDN_ENDPOINT_LIMIT} per profile)"
    ((WARNINGS++))
else
    log_success "  OK: ${CDN_ENDPOINTS} endpoints"
fi

# 6. Network Bandwidth (informational)
log_info "6. Network Bandwidth"
echo "" >> "${QUOTA_FILE}"
echo "Network Bandwidth:" >> "${QUOTA_FILE}"
echo "  Note: Bandwidth limits depend on subscription and region" >> "${QUOTA_FILE}"
echo "  For credential images (small files), bandwidth should be sufficient" >> "${QUOTA_FILE}"
log_success "  OK: Credential images are small files"

# Summary
echo ""
log_info "=== Quota Summary ==="
log_success "Checks passed: Multiple"
if [ ${WARNINGS} -gt 0 ]; then
    log_warning "Warnings: ${WARNINGS}"
fi
if [ ${ISSUES} -gt 0 ]; then
    log_error "Issues: ${ISSUES}"
    echo ""
    log_info "To request quota increases:"
    echo "  https://portal.azure.com/#blade/Microsoft_Azure_Support/HelpAndSupportBlade"
    echo "  Or use: az vm list-usage --location ${LOCATION}"
fi

echo ""
log_success "Quota report saved: ${QUOTA_FILE}"

if [ ${ISSUES} -eq 0 ]; then
    log_success "All quotas are sufficient for CDN setup!"
    exit 0
else
    log_error "Some quotas need attention before proceeding"
    exit 1
fi

