#!/bin/bash
#
# Azure Quota Check Script
# Checks quotas for all non-US Azure regions
#

set -e

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

# Check if Azure CLI is installed
if ! command -v az &> /dev/null; then
    echo -e "${RED}Error: Azure CLI is not installed.${NC}"
    exit 1
fi

# Check if logged in
if ! az account show &> /dev/null; then
    echo -e "${YELLOW}Please log in to Azure...${NC}"
    az login
fi

echo -e "${BLUE}========================================${NC}"
echo -e "${BLUE}Azure Quota Check - All Non-US Regions${NC}"
echo -e "${BLUE}========================================${NC}"
echo ""

# Get all non-US regions
echo -e "${YELLOW}Fetching non-US regions...${NC}"
REGIONS=$(az account list-locations \
    --query "[?metadata.regionType=='Physical' && !contains(name, 'us')].name" \
    -o tsv)

REGION_COUNT=$(echo "${REGIONS}" | wc -l)
echo -e "${GREEN}Found ${REGION_COUNT} non-US regions${NC}"
echo ""

# Output file
QUOTA_FILE="azure-quotas-all-regions.txt"
> "${QUOTA_FILE}"

echo "Azure Quota Report - All Non-US Regions" >> "${QUOTA_FILE}"
echo "Generated: $(date)" >> "${QUOTA_FILE}"
echo "Subscription: $(az account show --query name -o tsv)" >> "${QUOTA_FILE}"
echo "========================================" >> "${QUOTA_FILE}"
echo "" >> "${QUOTA_FILE}"

# Check quotas for each region
REGION_INDEX=0
for region in ${REGIONS}; do
    REGION_INDEX=$((REGION_INDEX + 1))
    echo -e "${BLUE}[${REGION_INDEX}/${REGION_COUNT}] Checking ${region}...${NC}"
    
    echo "" >> "${QUOTA_FILE}"
    echo "========================================" >> "${QUOTA_FILE}"
    echo "Region: ${region}" >> "${QUOTA_FILE}"
    echo "========================================" >> "${QUOTA_FILE}"
    
    # VM quotas
    echo "VM Family Quotas:" >> "${QUOTA_FILE}"
    az vm list-usage --location "${region}" -o table >> "${QUOTA_FILE}" 2>/dev/null || echo "  Unable to fetch VM quotas" >> "${QUOTA_FILE}"
    echo "" >> "${QUOTA_FILE}"
    
    # Storage quotas
    echo "Storage Account Quota:" >> "${QUOTA_FILE}"
    az storage account show-usage --location "${region}" -o json >> "${QUOTA_FILE}" 2>/dev/null || echo "  Unable to fetch storage quotas" >> "${QUOTA_FILE}"
    echo "" >> "${QUOTA_FILE}"
    
    # Network quotas
    echo "Network Quotas:" >> "${QUOTA_FILE}"
    az network list-usages --location "${region}" -o table >> "${QUOTA_FILE}" 2>/dev/null || echo "  Unable to fetch network quotas" >> "${QUOTA_FILE}"
    echo "" >> "${QUOTA_FILE}"
done

echo ""
echo -e "${GREEN}✓ Quota check complete${NC}"
echo -e "${GREEN}✓ Results saved to: ${QUOTA_FILE}${NC}"
echo ""

