#!/bin/bash
# Fix .env file to ensure proper ARM_* variable mapping for Terraform
# Adds ARM_* aliases for AZURE_* variables if they don't exist

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
ENV_FILE="$PROJECT_ROOT/.env"
BACKUP_FILE="${ENV_FILE}.backup.$(date +%Y%m%d_%H%M%S)"

if [ ! -f "$ENV_FILE" ]; then
  echo "❌ .env file not found at: $ENV_FILE"
  exit 1
fi

echo "🔧 Fixing .env file variable mapping..."
echo ""

# Backup original
cp "$ENV_FILE" "$BACKUP_FILE"
echo "✓ Backup created: $BACKUP_FILE"
echo ""

# Load current values
set -a
source "$ENV_FILE"
set +a

# Check what needs to be added
ADDITIONS=()

if [ -n "$AZURE_SUBSCRIPTION_ID" ] && [ -z "$ARM_SUBSCRIPTION_ID" ]; then
  ADDITIONS+=("ARM_SUBSCRIPTION_ID=\"$AZURE_SUBSCRIPTION_ID\"")
fi

if [ -n "$AZURE_TENANT_ID" ] && [ -z "$ARM_TENANT_ID" ]; then
  ADDITIONS+=("ARM_TENANT_ID=\"$AZURE_TENANT_ID\"")
fi

if [ -n "$AZURE_LOCATION" ] && [ -z "$ARM_LOCATION" ]; then
  ADDITIONS+=("ARM_LOCATION=\"$AZURE_LOCATION\"")
fi

# Add TF_VAR_environment if not set
if [ -z "$TF_VAR_environment" ]; then
  ADDITIONS+=("TF_VAR_environment=\"dev\"")
fi

if [ ${#ADDITIONS[@]} -eq 0 ]; then
  echo "✅ No fixes needed - all variables are properly mapped"
  rm -f "$BACKUP_FILE"
  exit 0
fi

echo "Adding the following variables:"
for var in "${ADDITIONS[@]}"; do
  echo "  + $var"
done
echo ""

# Append to .env file
echo "" >> "$ENV_FILE"
echo "# Terraform ARM variables (auto-added by azure-fix-env-mapping.sh)" >> "$ENV_FILE"
for var in "${ADDITIONS[@]}"; do
  echo "$var" >> "$ENV_FILE"
done

echo "✅ .env file updated!"
echo ""
echo "Changes:"
echo "  • Added ${#ADDITIONS[@]} variable(s)"
echo "  • Backup saved to: $BACKUP_FILE"
echo ""
echo "To verify:"
echo "  ./infra/scripts/azure-validate-current-env.sh"

