#!/usr/bin/env bash
set -euo pipefail

# Helper script to generate terraform import commands for existing resource groups
# that match the global multi-region naming convention.
#
# This is a dry-run helper: it only PRINTS terraform import commands.
# Review them and run manually as needed.
#
# Usage:
#   scripts/terraform/import-existing-rgs.sh

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
TERRAFORM_DIR="$PROJECT_ROOT/terraform"

cd "$TERRAFORM_DIR"

echo "Discovering existing Azure resource groups matching pattern 'az-p-*-rg-comp-001'..."

RG_LIST="$(az group list --query "[?contains(name, '-rg-comp-001')].name" -o tsv || true)"

if [[ -z "$RG_LIST" ]]; then
  echo "No matching resource groups found."
  exit 0
fi

echo
echo "Existing compute resource groups:"
echo "$RG_LIST"
echo

echo "Proposed terraform import commands:"
echo

while IFS= read -r RG; do
  # Example name: az-p-nor-rg-comp-001
  # Extract region code (3rd dash-separated segment)
  REGION_CODE="$(echo "$RG" | awk -F'-' '{print $3}')"

  # Map region code to region name via locals.tf region_codes (best effort)
  REGION_NAME="$(grep -E "^[[:space:]]*${REGION_CODE}[[:space:]]*=" locals.tf 2>/dev/null | awk -F'=' '{print $1}' | tr -d '[:space:]' || true)"

  echo "# Resource group: ${RG}"
  echo "# Region code guess: ${REGION_CODE}  Region name key: ${REGION_NAME:-<unknown>}"
  echo "terraform import 'azurerm_resource_group.global_multi_region[\"${REGION_NAME:-<region-key>}\"]' \"/subscriptions/<SUBSCRIPTION_ID>/resourceGroups/${RG}\""
  echo
done <<< "$RG_LIST"

echo "NOTE: Replace <SUBSCRIPTION_ID> and <region-key> as appropriate before running imports."


