#!/usr/bin/env bash
# Get Application Gateway IP
# Helper script to get the public IP address of the Application Gateway

set -euo pipefail


# Configuration
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/../lib/init.sh"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
# Load .env via dotenv (RPC CR/LF trim). Fallback: raw source.
if [[ -f "$SCRIPT_DIR/../lib/deployment/dotenv.sh" ]]; then
  # shellcheck disable=SC1090
  source "$SCRIPT_DIR/../lib/deployment/dotenv.sh"
  load_deployment_env --repo-root "${PROJECT_ROOT:-$REPO_ROOT}"
elif [[ -n "${PROJECT_ROOT:-}" && -f "$PROJECT_ROOT/.env" ]]; then
  set -a
  # shellcheck disable=SC1090
  source "$PROJECT_ROOT/.env"
  set +a
elif [[ -n "${REPO_ROOT:-}" && -f "$REPO_ROOT/.env" ]]; then
  set -a
  # shellcheck disable=SC1090
  source "$REPO_ROOT/.env"
  set +a
fi

# Load environment variables
if [ -f "${PROJECT_ROOT}/.env" ]; then
    set -a
    source "${PROJECT_ROOT}/.env"
    set +a
fi

AZURE_RESOURCE_GROUP="${AZURE_RESOURCE_GROUP:-defi-oracle-mainnet-rg}"

# Logging function
log() {
    log_success "[$(date +'%Y-%m-%d %H:%M:%S')] $1"
}

error() {
    log_error "[ERROR] $1"
    exit 1
}

warn() {
    log_warn "[WARNING] $1"
}

# Get Application Gateway IP from Terraform output
get_ip_from_terraform() {
    cd "${PROJECT_ROOT}/terraform" || error "Failed to change directory to terraform"
    
    if [ ! -f "terraform.tfstate" ] && [ ! -d ".terraform" ]; then
        return 1
    fi
    
    APP_GATEWAY_NAME=$(terraform output -raw app_gateway_name 2>/dev/null || echo "")
    
    if [ -z "$APP_GATEWAY_NAME" ]; then
        return 1
    fi
    
    cd "${PROJECT_ROOT}" || error "Failed to change directory to project root"
    
    # Get IP from Azure
    APP_GATEWAY_IP=$(az network application-gateway show \
        --resource-group "$AZURE_RESOURCE_GROUP" \
        --name "$APP_GATEWAY_NAME" \
        --query "frontendIPConfigurations[0].publicIpAddress.id" \
        -o tsv 2>/dev/null | xargs az network public-ip show --ids --query ipAddress -o tsv 2>/dev/null || echo "")
    
    if [ -n "$APP_GATEWAY_IP" ]; then
        echo "$APP_GATEWAY_IP"
        return 0
    fi
    
    return 1
}

# Get Application Gateway IP from Azure directly
get_ip_from_azure() {
    # List all application gateways in the resource group
    APP_GATEWAY_NAME=$(az network application-gateway list \
        --resource-group "$AZURE_RESOURCE_GROUP" \
        --query "[0].name" \
        -o tsv 2>/dev/null || echo "")
    
    if [ -z "$APP_GATEWAY_NAME" ] || [ "$APP_GATEWAY_NAME" = "null" ]; then
        return 1
    fi
    
    # Get public IP address
    APP_GATEWAY_IP=$(az network application-gateway show \
        --resource-group "$AZURE_RESOURCE_GROUP" \
        --name "$APP_GATEWAY_NAME" \
        --query "frontendIPConfigurations[0].publicIpAddress.id" \
        -o tsv 2>/dev/null | xargs az network public-ip show --ids --query ipAddress -o tsv 2>/dev/null || echo "")
    
    if [ -n "$APP_GATEWAY_IP" ]; then
        echo "$APP_GATEWAY_IP"
        return 0
    fi
    
    return 1
}

# Main function
main() {
    log "Getting Application Gateway IP address..."
    
    # Try to get from Terraform output first
    if APP_GATEWAY_IP=$(get_ip_from_terraform); then
        log "Application Gateway IP (from Terraform): $APP_GATEWAY_IP"
        echo "$APP_GATEWAY_IP"
        return 0
    fi
    
    # Try to get from Azure directly
    if APP_GATEWAY_IP=$(get_ip_from_azure); then
        log "Application Gateway IP (from Azure): $APP_GATEWAY_IP"
        echo "$APP_GATEWAY_IP"
        return 0
    fi
    
    error "Failed to get Application Gateway IP address. Please check:"
    error "  1. Azure credentials are configured"
    error "  2. Resource group exists: $AZURE_RESOURCE_GROUP"
    error "  3. Application Gateway is deployed"
    error "  4. Application Gateway has a public IP address"
}

# Run main function
main "$@"

