#!/usr/bin/env bash
# Script 1 of 3: sets up the Azure connection. Runs one or more of --steps
# aws-identity, azure-identity, connectors (default: all three, in that order).
#
# aws-identity turns on AWS outbound identity federation and creates or updates the
# IAM role (and its trust statements/inline policy) that the CloudWatch and AWS
# Config Azure connectors assume into. It is AWS-only: it never touches Azure.
#
# azure-identity is Azure-only. For one AWS consumer (account + region)
# connecting to this tenant, it creates or exactly adopts the telemetry
# identity and, unless --telemetry-only is set, the Config identity:
#   1. TELEMETRY identity: one single-tenant Entra application + service
#      principal, one federated credential for the supplied AWS issuer and IAM
#      role, and Reader plus Monitoring Reader at the tenant root management group.
#      Reader is sufficient for discovery, including Azure Resource Graph reads;
#      Monitoring Reader permits metric-value reads.
#   2. CONFIG identity: a second Entra application + service principal for AWS
#      Config, one federated credential whose subject is the AWS Config
#      third-party service-linked role, and Reader at the tenant root MG.
#
# The tenant is taken from the signed-in Azure CLI context rather than passed in.
# Before any change the script prints the tenant AND the full plan - every display
# name, federated subject, and role grant - then waits for confirmation.
# There is deliberately no unattended mode: bootstrapping federated trust and
# tenant-root Reader into an unintended tenant is the failure being prevented, a wrong
# ambient CLI context is how it happens, and a human reading the plan is the only guard
# that reliably catches it.
#
# Both applications are PER-CONSUMER: there is one telemetry app and, when
# requested, one Config app per (AWS account, AWS region), not one shared app for
# the tenant. Each is found by its own per-consumer ownership tags - the
# telemetry app by aws-cloudwatch-ingestion-account/-region and the Config app
# by aws-config-account/-region - the same mechanism for both. Display names are
# always derived and are never used to find an existing app. Each created app
# carries EXACTLY ONE federated credential; before the tenant-root RBAC grant the
# full credential set is re-read and every credential's (name, issuer, subject,
# audiences) tuple must match, so any extra, missing, or rewritten credential is
# treated as tampering and the script fails closed.
#
# The Config identity is named for AWS Config, not for CloudWatch. It is the
# identity the customer's AWS Config connector authenticates as, it is visible in
# their Entra portal, and it is owned by a different AWS service than the
# telemetry identity. Labelling it "cloudwatch" would mislabel it permanently:
# renaming a customer-visible identity later is a breaking migration for every
# already-onboarded tenant.
#
# App registrations and federated credentials are Microsoft Entra (Graph)
# objects that Script 2 does not create - its main.bicep at most looks up the
# telemetry service principal - so both identities are minted here.
#
# The telemetry identity gets Monitoring Reader for Azure Monitor metric-value reads.
# The Config identity remains Reader-only. The script does NOT create any Event Hub,
# diagnostic setting, VNet flow-log infrastructure, the activitylog hub, the Config
# diagnostic exports, the AWS Config connector, or any AWS-side IAM.
#
# Progress is written to stderr. Stdout contains exactly one JSON object, pretty-printed
# when stdout is a terminal and compact when it's redirected or piped: on success {status,
# steps, aws?, azure?, connectors?, warnings} (aws/azure/connectors present only for the
# steps this run actually selected), on failure {status: "failed", failedStep, error, fix,
# completedSteps, preFlightErrors} plus whatever of aws/azure/connectors had already been
# determined. When azure-identity runs without connectors, today's
# {"tenantId","appId","configAppId"} line
# is also printed to stderr.

set -euo pipefail

exec 3>&1

export AZURE_EXTENSION_USE_DYNAMIC_INSTALL=no
export LC_ALL=C

MIN_AZ_VERSION="2.47.0"
MIN_JQ_VERSION="1.6"
APP_NAME=""
AUDIENCE="api://AzureADTokenExchange"
DRY_RUN=false
TELEMETRY_ONLY=false
LOG_FILE=""
CURRENT_STEP_LABEL=""
COMPLETED_STEPS=()

ALL_STEPS="aws-identity azure-identity connectors"
STEPS="aws-identity,azure-identity,connectors"

TELEMETRY_FED_CRED_NAME="aws-cloudwatch-ingestion-federation"
TELEMETRY_FED_CRED_DESCRIPTION="AWS IAM Outbound Identity Federation for AWS CloudWatch Ingestion"
CONFIG_FED_CRED_NAME="aws-config-federation"
CONFIG_FED_CRED_DESCRIPTION="AWS IAM Outbound Identity Federation for AWS Config"

TENANT_ID=""
AWS_ISSUER_URL=""
AWS_ROLE_ARN=""
AWS_REGION=""
AWS_ACCOUNT_ID=""
AWS_ROLE_NAME=""
CONNECTION_NAME=""
AZURE_TENANT_ID_FLAG=""
TELEMETRY_APP_ID_FLAG=""
CONFIG_APP_ID_FLAG=""

READER_ROLE_ID="acdd72a7-3385-48ef-bd42-f606fba81ae7"
MONITORING_READER_ROLE_ID="43d0d8ad-25c7-4714-9337-8ba259a9fe05"

CONNECTOR_SERVICE_PRINCIPAL="observabilityadmin.amazonaws.com"
PIPELINE_SERVICE_PRINCIPAL="telemetry-pipelines.observabilityadmin.amazonaws.com"
TOKEN_EXCHANGE_POLICY_NAME="CloudWatchConnectorTokenExchange"

usage() {
    print_usage_overview
    print_usage_required
    print_usage_conditional_required
    print_usage_options
    print_usage_examples
    exit "${1:-2}"
}

print_usage_overview() {
    cat >&2 <<EOF
Usage: $0 --aws-region <region> [options]

By default this runs --steps aws-identity,azure-identity,connectors: it signs in
with the active AWS CLI credentials to set up the AWS side, uses the signed-in
Azure CLI context ('az login') to set up the Azure side, then creates the AWS
connectors. The Azure tenant is never selected by an argument; run
'az account show' to see which tenant that is. Before making any Azure change
the script prints the tenant and everything it will provision, and asks for
confirmation. This must be run interactively: there is no unattended mode,
because reviewing that plan is what prevents federated trust being bootstrapped
into the wrong tenant.
EOF
}

print_usage_required() {
    cat >&2 <<EOF

Required:
  --aws-region <region>    AWS region for the connector role, the per-consumer
                            ownership tags, and the per-consumer app names
                            (e.g. us-east-1)
EOF
}

print_usage_conditional_required() {
    cat >&2 <<EOF

Required when --steps includes aws-identity or connectors (the default):
  --aws-role-name <name>   Connector IAM role name. The script builds the role
                            ARN from the signed-in AWS account.

Required when --steps includes connectors (the default):
  --connection-name <name> CloudWatch connector name. The CloudWatch console uses it
                           to find the connection afterwards.

Required when --steps includes azure-identity without aws-identity (for
example, running azure-identity alone in Azure Cloud Shell, which has no AWS
credentials):
  --aws-issuer-url <url>   AWS IAM Outbound Identity Federation issuer URL
  --aws-role-arn <arn>     AWS IAM role ARN used as the telemetry federated
                           subject; its account id also derives the Config
                           service-linked-role subject and the ownership tags

Required when --steps includes connectors without azure-identity (identities
already exist from an earlier run):
  --azure-tenant-id <guid>   Azure tenant ID from an earlier azure-identity run
  --telemetry-app-id <guid>  Telemetry application (client) ID from that run
  --config-app-id <guid>     Config application (client) ID from that run;
                             not needed with --telemetry-only
EOF
}

print_usage_options() {
    cat >&2 <<EOF

Options:
  --steps <list>                 Comma-separated steps to run, in any mix of
                                  ${ALL_STEPS// /, }. Default: all three.
  --telemetry-only               Create only the CloudWatch telemetry identity
  --dry-run                      Validate and print planned changes without mutation
  -h, --help                     Show this help

Application display names are always derived and cannot be overridden:
  telemetry: "AWS CloudWatch Ingestion <awsAccount>-<awsRegion>"
  Config:    "AWS Config <awsAccount>-<awsRegion>"
Existing applications are found by their ownership tags, never by name.

Progress goes to stderr; the summary JSON (status, steps, aws/azure/connectors
details, warnings) goes to stdout. On failure, stdout gets a JSON object with
"status":"failed" instead.
EOF
}

print_usage_examples() {
    cat >&2 <<EOF

Examples, one per run mode:

  All three steps (default):
    $0 --aws-region us-east-1 --aws-role-name CloudWatchAzureConnector \\
      --connection-name my-azure-connection

  aws-identity only:
    $0 --steps aws-identity --aws-region us-east-1 \\
      --aws-role-name CloudWatchAzureConnector

  azure-identity only (for example in Azure Cloud Shell, pasting back into
  the console as today):
    $0 --steps azure-identity --aws-region us-east-1 \\
      --aws-issuer-url https://<id>.tokens.sts.global.api.aws \\
      --aws-role-arn arn:aws:iam::123456789012:role/CloudWatchAzureConnector

  connectors only (identities already exist from an earlier run):
    $0 --steps connectors --aws-region us-east-1 \\
      --connection-name my-azure-connection --azure-tenant-id <guid> \\
      --telemetry-app-id <guid> --config-app-id <guid>

  aws-identity and azure-identity (two cloud shells, no connectors yet):
    $0 --steps aws-identity,azure-identity --aws-region us-east-1 \\
      --aws-role-name CloudWatchAzureConnector

  azure-identity and connectors (AWS identity already exists):
    $0 --steps azure-identity,connectors --aws-region us-east-1 \\
      --connection-name my-azure-connection
EOF
}

LAST_ERROR_MSG=""
LAST_ERROR_FIX=""

die() {
    local msg="$1"
    local fix="${2:-}"
    local detail="${3:-}"
    trap - ERR
    LAST_ERROR_MSG="${msg}"
    LAST_ERROR_FIX="${fix}"

    [[ -n "${LOG_FILE}" ]] && log "Log: ${LOG_FILE}" || true
    echo "..................................................." >&2
    {
        echo "Error: ${msg}"
        [[ -n "${fix}" ]] && echo "Fix: ${fix}" || true
        [[ -n "${detail}" ]] && echo "${detail}" || true
    } >&2
    if [[ -n "${LOG_FILE}" ]]; then
        {
            echo "Error: ${msg}"
            [[ -n "${fix}" ]] && echo "Fix: ${fix}" || true
            [[ -n "${detail}" ]] && echo "${detail}" || true
        } >> "${LOG_FILE}"
    fi
    print_completion_status
    print_failure_json
    exit 1
}

die_usage() {
    echo "Error: $1" >&2
    exit 2
}

log() {
    echo "[INFO] $1" >&2
    [[ -n "${LOG_FILE}" ]] && echo "[INFO] $1" >> "${LOG_FILE}" || true
}

WARNINGS=()

warn() {
    echo "[WARN] $1" >&2
    [[ -n "${LOG_FILE}" ]] && echo "[WARN] $1" >> "${LOG_FILE}" || true
    WARNINGS+=("$1")
}

COMMAND_ISSUES=()
AWS_ISSUES=()
AZURE_ISSUES=()
HAVE_JQ=true
HAVE_AWS_CLI=true
HAVE_AZ_CLI=true
HAVE_AWS_CONTEXT=true
HAVE_AZURE_CONTEXT=true

add_issue() {
    local category="$1"
    local message="$2"
    case "${category}" in
        command) COMMAND_ISSUES+=("${message}") ;;
        aws) AWS_ISSUES+=("${message}") ;;
        azure) AZURE_ISSUES+=("${message}") ;;
        *) die "Internal error: add_issue called with unknown category '${category}'." ;;
    esac
}

preflight_issue_count() {
    echo $((${#COMMAND_ISSUES[@]} + ${#AWS_ISSUES[@]} + ${#AZURE_ISSUES[@]}))
}

append_preflight_section() {
    local heading="$1"
    shift
    local issues=("$@")
    local issue

    [[ ${#issues[@]} -gt 0 ]] || return 0
    PREFLIGHT_DETAIL+=$'\n'"${heading}:"
    for issue in "${issues[@]}"; do
        PREFLIGHT_DETAIL+=$'\n'"  - ${issue}"
    done
    PREFLIGHT_DETAIL+=$'\n'
}

report_preflight_issues() {
    local count
    count=$(preflight_issue_count)
    [[ "${count}" -gt 0 ]] || return 0

    local PREFLIGHT_DETAIL=""
    [[ ${#COMMAND_ISSUES[@]} -eq 0 ]] || append_preflight_section "Command prerequisites" "${COMMAND_ISSUES[@]}"
    [[ ${#AWS_ISSUES[@]} -eq 0 ]] || append_preflight_section "AWS prerequisites" "${AWS_ISSUES[@]}"
    [[ ${#AZURE_ISSUES[@]} -eq 0 ]] || append_preflight_section "Azure prerequisites" "${AZURE_ISSUES[@]}"
    die "Preflight found ${count} issue(s). Resolve all of them, then re-run the same command." "" "${PREFLIGHT_DETAIL%$'\n'}"
}

to_status() {
    case "$1" in
        create) echo "created" ;;
        update) echo "updated" ;;
        existing) echo "existing" ;;
        *) echo "$1" ;;
    esac
}

STEP_LABELS=()

build_step_labels() {
    STEP_LABELS=("Checking permissions")
    if has_step aws-identity; then
        STEP_LABELS+=("AWS outbound identity federation" "AWS connector role")
    fi
    has_step azure-identity && STEP_LABELS+=("Microsoft Entra applications")
    if has_step connectors; then
        STEP_LABELS+=("Connectors" "Verifying Azure access")
    fi
}

step_progress() {
    local label="$1"
    local total="${#STEP_LABELS[@]}"
    local index

    CURRENT_STEP_LABEL="${label}"
    for index in "${!STEP_LABELS[@]}"; do
        if [[ "${STEP_LABELS[${index}]}" == "${label}" ]]; then
            log "[$((index + 1))/${total}] ${label}"
            return 0
        fi
    done
    log "${label}"
}

mark_step_completed() {
    COMPLETED_STEPS+=("$1")
}

print_completion_status() {
    local completed_line

    if [[ ${#COMPLETED_STEPS[@]} -eq 0 ]]; then
        completed_line="No changes were made."
    else
        completed_line=$(printf '%s, ' "${COMPLETED_STEPS[@]}")
        completed_line="Completed: ${completed_line%, }"
    fi

    {
        echo ""
        echo "${completed_line}"
        [[ -n "${CURRENT_STEP_LABEL}" ]] && echo "Failed:    ${CURRENT_STEP_LABEL}" || true
        [[ -n "${LOG_FILE}" ]] && echo "Log:       ${LOG_FILE}" || true
    } >&2
    if [[ -n "${LOG_FILE}" ]]; then
        {
            echo ""
            echo "${completed_line}"
            [[ -n "${CURRENT_STEP_LABEL}" ]] && echo "Failed:    ${CURRENT_STEP_LABEL}" || true
            echo "Log:       ${LOG_FILE}"
        } >> "${LOG_FILE}"
    fi
}

on_error() {
    local line="$1"
    local msg="Unexpected failure at line ${line}."
    trap - ERR
    LAST_ERROR_MSG="${msg}"
    LAST_ERROR_FIX=""
    echo "Error: ${msg}" >&2
    [[ -n "${LOG_FILE}" ]] && echo "Error: ${msg}" >> "${LOG_FILE}" || true
    print_completion_status
    print_failure_json
    exit 1
}

capitalize() {
    printf '%s%s' "$(printf '%s' "${1:0:1}" | tr '[:lower:]' '[:upper:]')" "${1:1}"
}

read_optional() {
    local label="$1"
    local not_found_pattern="$2"
    local output
    local error_file
    local error_output
    local status=0
    shift 2

    error_file=$(mktemp "${TMPDIR:-/tmp}/cloudwatch-azure-cli-error.XXXXXX") ||
        die "Failed to create a temporary file to inspect ${label}."
    output=$("$@" 2>"${error_file}") || status=$?
    error_output=$(cat -- "${error_file}")
    rm -f -- "${error_file}"

    if [[ ${status} -eq 0 ]]; then
        echo "${output}" | jq -e . >/dev/null ||
            die "$(capitalize "${label}") returned invalid JSON."
        printf '%s' "${output}"
    elif grep -Eqi "${not_found_pattern}" <<< "${error_output}"; then
        return 0
    else
        die "Failed to inspect ${label}." "re-run with the same flags; the rerun adopts what this run already created." "${error_output}"
    fi
}

read_optional_json() {
    read_optional "$1" 'ResourceNotFound|NotFound|could not be found|was not found|does not exist|No application found' "${@:2}"
}

read_optional_aws_json() {
    read_optional "$1" 'NoSuchEntity' "${@:2}"
}

trust_statement_sid() {
    local prefix="$1"
    local region="$2"
    local principal="$3"
    local stage="Internal"

    [[ "${principal}" == *.amazonaws.com ]] && stage="Prod" || true
    printf '%s' "${prefix}${region}${stage}" | tr -cd '[:alnum:]'
}

require_value() {
    if [[ $# -lt 2 || -z "${2}" || "${2}" == --* ]]; then
        echo "Error: $1 requires a value." >&2
        usage
    fi
}

is_guid() {
    [[ "$1" =~ ^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$ ]]
}

has_step() {
    [[ " ${STEPS//,/ } " == *" $1 "* ]]
}

validate_steps() {
    local requested="${STEPS//,/ }"
    local step
    local seen=""

    [[ -n "${STEPS}" ]] || die_usage "--steps may not be empty."
    for step in ${requested}; do
        [[ " ${ALL_STEPS} " == *" ${step} "* ]] ||
            die_usage "--steps names an unknown step '${step}'. Valid steps: ${ALL_STEPS// /, }."
        [[ " ${seen} " != *" ${step} "* ]] || die_usage "--steps names '${step}' more than once."
        seen="${seen} ${step}"
    done
}

version_at_least() {
    local current="$1"
    local minimum="$2"
    local current_parts
    local minimum_parts
    local i

    IFS='.' read -r -a current_parts <<< "${current%%-*}"
    IFS='.' read -r -a minimum_parts <<< "${minimum%%-*}"
    for i in 0 1 2; do
        if (( ${current_parts[$i]:-0} > ${minimum_parts[$i]:-0} )); then
            return 0
        fi
        if (( ${current_parts[$i]:-0} < ${minimum_parts[$i]:-0} )); then
            return 1
        fi
    done
    return 0
}

run_azure() {
    if [[ "${DRY_RUN}" == true ]]; then
        return 0
    else
        "$@"
    fi
}

permission_allowed() {
    local permissions_json="$1"
    local desired
    local index
    local count
    local action
    local denied
    local action_matches
    local denied_matches

    desired=$(echo "$2" | tr '[:upper:]' '[:lower:]')
    count=$(echo "${permissions_json}" | jq -r '.value | length')
    index=0
    while [[ ${index} -lt ${count} ]]; do
        action_matches=false
        denied_matches=false

        while IFS= read -r action; do
            action=$(echo "${action}" | tr '[:upper:]' '[:lower:]')
            # shellcheck disable=SC2053
            if [[ "${desired}" == ${action} ]]; then
                action_matches=true
                break
            fi
        done < <(echo "${permissions_json}" | jq -r ".value[${index}].actions[]?")

        while IFS= read -r denied; do
            denied=$(echo "${denied}" | tr '[:upper:]' '[:lower:]')
            # shellcheck disable=SC2053
            if [[ "${desired}" == ${denied} ]]; then
                denied_matches=true
                break
            fi
        done < <(echo "${permissions_json}" | jq -r ".value[${index}].notActions[]?")

        if [[ "${action_matches}" == true && "${denied_matches}" == false ]]; then
            return 0
        fi
        index=$((index + 1))
    done
    return 1
}

is_authorization_failure() {
    grep -Eqi "AuthorizationFailed|does not have authorization to perform action" <<< "$1"
}

validate_effective_roles_at_scope() {
    local principal_id="$1"
    local scope="$2"
    local label="$3"
    local assignments
    local allowed_roles
    local offending
    shift 3

    allowed_roles=$(printf '%s\n' "$@" |
        jq -Rsc 'split("\n") | map(select(length > 0) | ascii_downcase)')
    assignments=$(az role assignment list \
        --assignee "${principal_id}" \
        --scope "${scope}" \
        --include-inherited \
        --output json)

    if ! echo "${assignments}" | jq -e \
        --arg principalId "${principal_id}" \
        --arg scope "${scope}" \
        --argjson allowedRoles "${allowed_roles}" \
        '
        all(.[];
            ((.principalId | ascii_downcase) == ($principalId | ascii_downcase))
            and ((.scope | ascii_downcase) == ($scope | ascii_downcase))
            and ((.roleDefinitionId | split("/") | last | ascii_downcase) as $roleId
                | ($allowedRoles | index($roleId)) != null))
        ' >/dev/null; then
        offending=$(echo "${assignments}" | jq -r \
            --arg principalId "${principal_id}" \
            --arg scope "${scope}" \
            --argjson allowedRoles "${allowed_roles}" \
            '
            [.[] | select(
                ((.principalId | ascii_downcase) != ($principalId | ascii_downcase))
                or ((.scope | ascii_downcase) != ($scope | ascii_downcase))
                or ((.roleDefinitionId | split("/") | last | ascii_downcase) as $roleId
                    | ($allowedRoles | index($roleId)) == null)
            ) | "\(.roleDefinitionName // (.roleDefinitionId | split("/") | last)) at \(.scope)"]
            | join(", ")
            ')
        die "$(capitalize "${label}") has an unexpected role assignment: ${offending}." \
            "Remove the unexpected role assignment(s), then rerun."
    fi
}

validate_no_graph_grants() {
    local principal_id="$1"
    local app_role_assignments
    local oauth_grants

    app_role_assignments=$(az rest \
        --method get \
        --url "https://graph.microsoft.com/v1.0/servicePrincipals/${principal_id}/appRoleAssignments" \
        --output json)
    oauth_grants=$(az rest \
        --method get \
        --url "https://graph.microsoft.com/v1.0/oauth2PermissionGrants?\$filter=clientId%20eq%20%27${principal_id}%27" \
        --output json)

    if ! echo "${app_role_assignments}" | jq -e '(.value // []) | length == 0' >/dev/null ||
        ! echo "${oauth_grants}" | jq -e '(.value // []) | length == 0' >/dev/null; then
        die "Service principal has unexpected Microsoft Graph application or delegated grants."
    fi
}

merge_graph_tags() {
    local collection="$1"
    local object_id="$2"
    local desired="$3"
    local existing
    local merged

    if [[ "${DRY_RUN}" == true ]]; then
        return 0
    fi

    existing=$(az rest \
        --method get \
        --url "https://graph.microsoft.com/v1.0/${collection}/${object_id}?\$select=tags" \
        --output json | jq -c '.tags // []')
    merged=$(jq -cn --argjson existing "${existing}" --argjson desired "${desired}" \
        '($existing + $desired) | unique')
    az rest \
        --method patch \
        --url "https://graph.microsoft.com/v1.0/${collection}/${object_id}" \
        --body "$(jq -cn --argjson tags "${merged}" '{tags: $tags}')" \
        --output none
}

find_existing_app_by_tag() {
    local tags_json="$1"
    local matches
    local match_count

    matches=$(az ad app list --all --output json 2>/dev/null |
        jq -c --argjson required "${tags_json}" \
            '[.[] | select((($required - (.tags // [])) | length) == 0)]') || return 0
    match_count=$(echo "${matches}" | jq -r 'length' 2>/dev/null) || return 0
    [[ "${match_count}" == "1" ]] || return 0
    echo "${matches}" | jq -r '.[0].appId'
}

ensure_application_by_tag() {
    local display_name="$1"
    local tags_json="$2"
    local identifier_uri="${3:-}"
    local tag_list

    [[ "$(echo "${tags_json}" | jq -r 'length')" -gt 0 ]] ||
        die "Internal error: ensure_application_by_tag requires at least one ownership tag."
    tag_list=$(echo "${tags_json}" | jq -r 'join(" + ")')

    MATCHED_APP_JSON=""
    find_app_by_ownership_tag "${tags_json}" "${tag_list}"
    if [[ -n "${MATCHED_APP_JSON}" ]]; then
        adopt_application_by_tag "${MATCHED_APP_JSON}" "${display_name}"
        return 0
    fi

    check_display_name_collision "${display_name}" "${tag_list}"
    check_identifier_uri_collision "${identifier_uri}" "${tag_list}"
    create_application "${display_name}" "${tags_json}" "${identifier_uri}"
}

find_app_by_ownership_tag() {
    local tags_json="$1"
    local tag_list="$2"
    local matches
    local match_count

    matches=$(az ad app list --all --output json |
        jq -c --argjson required "${tags_json}" \
            '[.[] | select((($required - (.tags // [])) | length) == 0)]') ||
        die "Failed to list applications to match ownership tags ${tag_list}, so this run stopped without creating one."
    match_count=$(echo "${matches}" | jq -r 'length')
    [[ "${match_count}" =~ ^[0-9]+$ ]] ||
        die "az ad app list returned no JSON array, so this run stopped without creating one."
    if [[ "${match_count}" -gt 1 ]]; then
        local object_ids
        object_ids=$(echo "${matches}" | jq -r '[.[] | .id] | join(", ")')
        die "Multiple applications (object IDs: ${object_ids}) carry ownership tags ${tag_list}, so this run stopped rather than guess which one to use." \
            "delete the extra applications, keeping one, then rerun."
    fi
    if [[ "${match_count}" -eq 1 ]]; then
        MATCHED_APP_JSON=$(echo "${matches}" | jq -c '.[0]')
    fi
}

adopt_application_by_tag() {
    local app_json="$1"
    local display_name="$2"
    local app_id
    local app_object_id

    app_id=$(echo "${app_json}" | jq -r '.appId')
    app_object_id=$(echo "${app_json}" | jq -r '.id')
    if ! echo "${app_json}" | jq -e \
        '
        .signInAudience == "AzureADMyOrg"
          and ((.passwordCredentials // []) | length == 0)
          and ((.keyCredentials // []) | length == 0)
          and ((.requiredResourceAccess // []) | length == 0)
          and ((.web.redirectUris // []) | length == 0)
          and ((.spa.redirectUris // []) | length == 0)
          and ((.publicClient.redirectUris // []) | length == 0)
        ' >/dev/null; then
        die "Existing application ${app_id} already exists, but its sign-in audience, credentials, or redirect URIs don't match what this script expects. Fix those settings, or delete it and let this script recreate it, then re-run."
    fi
    log "Exactly adopted application ${app_id} ('${display_name}') by ownership tag."
    echo "${app_id} ${app_object_id} existing"
}

check_display_name_collision() {
    local display_name="$1"
    local tag_list="$2"
    local display_collisions
    local display_count

    display_collisions=$(az ad app list --display-name "${display_name}" --output json |
        jq -c --arg displayName "${display_name}" '[.[] | select(.displayName == $displayName)]') ||
        die "Failed to look up applications named '${display_name}', so this run stopped without creating a duplicate."
    display_count=$(echo "${display_collisions}" | jq -r 'length')
    [[ "${display_count}" =~ ^[0-9]+$ ]] ||
        die "az ad app list returned no JSON array for '${display_name}', so this run stopped without creating a duplicate."
    if [[ "${display_count}" -ne 0 ]]; then
        local display_collision_ids
        display_collision_ids=$(echo "${display_collisions}" | jq -r '[.[].id] | join(", ")')
        die "An application named '${display_name}' (object IDs: ${display_collision_ids}) exists but does not carry the ownership tags ${tag_list}, so this run stopped without creating a duplicate." \
            "Tag the existing application or delete it, then rerun."
    fi
}

check_identifier_uri_collision() {
    local identifier_uri="$1"
    local tag_list="$2"
    local uri_collisions_json
    local uri_collisions

    if [[ -n "${identifier_uri}" ]]; then
        uri_collisions_json=$(az ad app list --identifier-uri "${identifier_uri}" --output json) ||
            die "Failed to look up applications holding identifier URI ${identifier_uri}, so this run stopped without creating a duplicate."
        uri_collisions=$(echo "${uri_collisions_json}" | jq -r 'length')
        [[ "${uri_collisions}" =~ ^[0-9]+$ ]] ||
            die "az ad app list returned no JSON array for identifier URI ${identifier_uri}, so this run stopped without creating a duplicate."
        if [[ "${uri_collisions}" -ne 0 ]]; then
            local uri_collision_ids
            uri_collision_ids=$(echo "${uri_collisions_json}" | jq -r '[.[].id] | join(", ")')
            die "An application (object IDs: ${uri_collision_ids}) already holds identifier URI ${identifier_uri} but does not carry the ownership tags ${tag_list}, so this run stopped without creating a duplicate." \
                "Tag the existing application or delete it, then rerun."
        fi
    fi
}

create_application() {
    local display_name="$1"
    local tags_json="$2"
    local identifier_uri="$3"
    local body
    local app_json
    local app_id
    local app_object_id

    if [[ "${DRY_RUN}" == true ]]; then
        log "Would create the single-tenant application '${display_name}'."
        echo "<dry-run-app-id> <dry-run-app-object-id> created"
        return 0
    fi

    body=$(jq -cn --arg displayName "${display_name}" --argjson tags "${tags_json}" \
        '{displayName: $displayName, signInAudience: "AzureADMyOrg", tags: $tags}')
    if [[ -n "${identifier_uri}" ]]; then
        body=$(echo "${body}" | jq -c --arg uri "${identifier_uri}" '. + {identifierUris: [$uri]}')
    fi

    app_json=$(az rest \
        --method post \
        --url "https://graph.microsoft.com/v1.0/applications" \
        --body "${body}" \
        --output json) ||
        die "Failed to create the application '${display_name}'."
    app_id=$(echo "${app_json}" | jq -r '.appId')
    app_object_id=$(echo "${app_json}" | jq -r '.id')
    is_guid "${app_id}" || die "Microsoft Graph did not return a valid application client ID."
    is_guid "${app_object_id}" || die "Microsoft Graph did not return a valid application object ID."
    log "Created application ${app_id} ('${display_name}')."
    echo "${app_id} ${app_object_id} created"
}

ensure_service_principal() {
    local app_id="$1"
    local sp_json
    local sp_object_id

    if [[ "${DRY_RUN}" == true && "${app_id}" == "<dry-run-app-id>" ]]; then
        log "Would create the service principal for ${app_id}."
        echo "<dry-run-service-principal-id>"
        return 0
    fi

    sp_json=$(read_optional_json \
        "service principal for app ${app_id}" \
        az ad sp show --id "${app_id}" --output json) || exit 1
    if [[ -z "${sp_json}" ]]; then
        if [[ "${DRY_RUN}" == true ]]; then
            log "Would create the service principal for ${app_id}."
            echo "<dry-run-service-principal-id>"
            return 0
        fi
        sp_json=$(az ad sp create --id "${app_id}" --output json) ||
            die "Failed to create the service principal for ${app_id}."
        sp_object_id=$(echo "${sp_json}" | jq -r '.id')
        is_guid "${sp_object_id}" || die "Microsoft Graph did not return a valid service principal object ID."
        log "Created service principal ${sp_object_id}."
        echo "${sp_object_id}"
        return 0
    fi

    sp_object_id=$(echo "${sp_json}" | jq -r '.id')
    is_guid "${sp_object_id}" || die "Microsoft Graph did not return a valid service principal object ID."
    if ! echo "${sp_json}" | jq -e \
        --arg appId "${app_id}" \
        --arg tenantId "${TENANT_ID}" \
        '
        .appId == $appId
          and (.appOwnerOrganizationId | ascii_downcase) == $tenantId
          and .accountEnabled == true
          and .servicePrincipalType == "Application"
          and ((.passwordCredentials // []) | length == 0)
          and ((.keyCredentials // []) | length == 0)
        ' >/dev/null; then
        die "Existing service principal ${sp_object_id} already exists, but its settings don't match what this script expects. Fix those settings, or delete it and let this script recreate it, then re-run."
    fi
    log "Exactly adopted service principal ${sp_object_id}."
    echo "${sp_object_id}"
}

ensure_fic_by_name() {
    local app_id="$1" cred_name="$2" issuer="$3" subject="$4" audience="$5" description="$6"
    local params existing match match_count

    params=$(jq -cn \
        --arg name "${cred_name}" \
        --arg issuer "${issuer}" \
        --arg subject "${subject}" \
        --arg audience "${audience}" \
        --arg description "${description}" \
        '{
            name: $name,
            issuer: $issuer,
            subject: $subject,
            audiences: [$audience],
            description: $description
        }')

    if [[ "${DRY_RUN}" == true && "${app_id}" == "<dry-run-app-id>" ]]; then
        log "Would create federated credential '${cred_name}'."
        return 0
    fi

    existing=$(az ad app federated-credential list --id "${app_id}" --output json)
    match=$(echo "${existing}" | jq -c --arg name "${cred_name}" '[.[] | select(.name == $name)]')
    match_count=$(echo "${match}" | jq -r 'length')

    if [[ "${match_count}" -eq 0 ]]; then
        create_federated_credential "${app_id}" "${cred_name}" "${params}"
    else
        adopt_or_reject_federated_credential "${match}" "${match_count}" "${cred_name}" "${issuer}" "${subject}" "${audience}"
    fi
}

create_federated_credential() {
    local app_id="$1" cred_name="$2" params="$3"

    run_azure az ad app federated-credential create \
        --id "${app_id}" \
        --parameters "${params}" \
        --output none ||
        die "Failed to create federated credential '${cred_name}'."
    if [[ "${DRY_RUN}" == true ]]; then
        log "Would create federated credential '${cred_name}'."
    else
        log "Created federated credential '${cred_name}'."
    fi
}

adopt_or_reject_federated_credential() {
    local match="$1" match_count="$2" cred_name="$3" issuer="$4" subject="$5" audience="$6"
    local mismatches existing_id

    if [[ "${match_count}" -eq 1 ]] &&
        echo "${match}" | jq -e \
            --arg issuer "${issuer}" \
            --arg subject "${subject}" \
            --arg audience "${audience}" \
            '.[0].issuer == $issuer and .[0].subject == $subject and .[0].audiences == [$audience]' \
            >/dev/null; then
        log "Exactly adopted federated credential '${cred_name}'."
        return 0
    fi

    mismatches=$(echo "${match}" | jq -r \
        --arg issuer "${issuer}" --arg subject "${subject}" --arg audience "${audience}" \
        "
        [
            (if .[0].issuer != \$issuer then \"issuer (has \" + .[0].issuer + \", needs \" + \$issuer + \")\" else null end),
            (if .[0].subject != \$subject then \"subject (has \" + .[0].subject + \", needs \" + \$subject + \")\" else null end),
            (if (.[0].audiences != [\$audience]) then \"audience (has \" + (.[0].audiences | join(\",\")) + \", needs \" + \$audience + \")\" else null end)
        ] | map(select(. != null)) | join(\"; \")
        ")
    existing_id=$(echo "${match}" | jq -r '.[0].id // .[0].name')
    die "Existing federated credential '${cred_name}' (ID ${existing_id}) has the wrong ${mismatches}." \
        "Remove it and re-run; this script will recreate it."
}

fic_spec() {
    jq -cn \
        --arg name "$1" \
        --arg issuer "$2" \
        --arg subject "$3" \
        --arg audience "$4" \
        '{name: $name, issuer: $issuer, subject: $subject, audiences: [$audience]}'
}

assert_fic_set() {
    local app_id="$1"
    local expected="$2"
    local current
    local extra
    local missing
    local altered

    if [[ "${DRY_RUN}" == true ]]; then
        return 0
    fi

    current=$(az ad app federated-credential list --id "${app_id}" --output json)
    if echo "${current}" | jq -e --argjson expected "${expected}" \
        '([.[] | {name, issuer, subject, audiences}] | sort_by(.name))
           == ($expected | sort_by(.name))' >/dev/null; then
        return 0
    fi

    extra=$(echo "${current}" | jq -r --argjson expected "${expected}" \
        '([.[].name] - [$expected[].name]) | sort | join(", ")')
    missing=$(echo "${current}" | jq -r --argjson expected "${expected}" \
        '([$expected[].name] - [.[].name]) | sort | join(", ")')
    altered=$(echo "${current}" | jq -r --argjson expected "${expected}" \
        '([$expected[] | {key: .name, value: .}] | from_entries) as $want
         | [.[]
             | {name, issuer, subject, audiences} as $have
             | select($want[$have.name] != null and $have != $want[$have.name])
             | ($have.name + " (" +
                (["issuer", "subject", "audiences"]
                    | map(select($have[.] != $want[$have.name][.])) | join(", ")) +
                " differs)")]
         | join("; ")')

    local detail=""
    [[ -n "${extra}" ]] && detail="${detail}Unexpected credentials: ${extra}"$'\n'
    [[ -n "${missing}" ]] && detail="${detail}Missing credentials: ${missing}"$'\n'
    [[ -n "${altered}" ]] && detail="${detail}Altered credentials: ${altered}"$'\n'
    die "Application ${app_id} federated credentials do not match the expected trust set. This script never removes federated credentials; inspect the unexpected credentials in Microsoft Entra, then re-run the same command." "" "${detail%$'\n'}"
}

revalidate_identity() {
    local app_id="$1"
    local app_object_id="$2"
    local sp_object_id="$3"
    local tags_json="$4"
    local expected_fics="$5"
    local current_app
    local current_sp

    if [[ "${DRY_RUN}" == true ]]; then
        return 0
    fi

    current_app=$(az ad app show --id "${app_id}" --output json)
    current_sp=$(az ad sp show --id "${app_id}" --output json)

    echo "${current_app}" | jq -e \
        --arg appId "${app_id}" \
        --arg objectId "${app_object_id}" \
        --argjson expectedTags "${tags_json}" \
        '
        . as $app
        | .appId == $appId
          and .id == $objectId
          and .signInAudience == "AzureADMyOrg"
          and ((.passwordCredentials // []) | length == 0)
          and ((.keyCredentials // []) | length == 0)
          and ((.requiredResourceAccess // []) | length == 0)
          and ((.web.redirectUris // []) | length == 0)
          and ((.spa.redirectUris // []) | length == 0)
          and ((.publicClient.redirectUris // []) | length == 0)
          and (($app.tags // []) as $t | all($expectedTags[]; . as $x | ($t | index($x)) != null))
        ' >/dev/null || die "Application ${app_id} state changed before the tenant-root RBAC grant."

    echo "${current_sp}" | jq -e \
        --arg appId "${app_id}" \
        --arg objectId "${sp_object_id}" \
        --arg tenantId "${TENANT_ID}" \
        --argjson expectedTags "${tags_json}" \
        '
        . as $sp
        | .appId == $appId
          and .id == $objectId
          and (.appOwnerOrganizationId | ascii_downcase) == $tenantId
          and .accountEnabled == true
          and .servicePrincipalType == "Application"
          and ((.passwordCredentials // []) | length == 0)
          and ((.keyCredentials // []) | length == 0)
          and (($sp.tags // []) as $t | all($expectedTags[]; . as $x | ($t | index($x)) != null))
        ' >/dev/null || die "Service-principal ${sp_object_id} state changed before the tenant-root RBAC grant."

    assert_fic_set "${app_id}" "${expected_fics}"

    validate_no_graph_grants "${sp_object_id}"
}

assign_root_role() {
    local sp_object_id="$1"
    local label="$2"
    local role_id="$3"
    local role_name="$4"
    local error_output

    if [[ "${DRY_RUN}" == true || "${sp_object_id}" == "<dry-run-service-principal-id>" ]]; then
        log "Would assign ${role_name} to the ${label} service principal at the tenant root management group."
        return 0
    fi

    if error_output=$(az role assignment create \
        --assignee-object-id "${sp_object_id}" \
        --assignee-principal-type ServicePrincipal \
        --role "${role_id}" \
        --scope "${MANAGEMENT_GROUP_SCOPE}" \
        --output none 2>&1); then
        log "Assigned ${role_name} to the ${label} service principal at the tenant root management group."
    elif grep -Eqi "already exists|RoleAssignmentExists" <<< "${error_output}"; then
        log "Exactly adopted ${role_name} for the ${label} service principal at the tenant root management group."
    elif is_authorization_failure "${error_output}"; then
        die "The active principal cannot assign ${role_name} to the ${label} service principal at the tenant root management group ${TENANT_ID} (authorization failed): ${error_output//$'\n'/ }" \
            "resolve the Azure CLI error, then re-run with the same flags; the rerun adopts what this run already created."
    else
        die "Failed to assign ${role_name} to the ${label} service principal." \
            "resolve the Azure CLI error, then re-run with the same flags; the rerun adopts what this run already created." \
            "${error_output}"
    fi
}

assign_root_reader() {
    assign_root_role "$1" "$2" "${READER_ROLE_ID}" "Reader"
}

assign_root_monitoring_reader() {
    assign_root_role "$1" "$2" "${MONITORING_READER_ROLE_ID}" "Monitoring Reader"
}

parse_args() {
    while [[ $# -gt 0 ]]; do
        case "$1" in
            --steps | --aws-issuer-url | --aws-role-arn | --aws-role-name | --connection-name | \
                --azure-tenant-id | --telemetry-app-id | --config-app-id | --aws-region)
                require_value "$@"
                assign_flag_value "$1" "$2"
                shift 2
                ;;
            --telemetry-only)
                TELEMETRY_ONLY=true
                shift
                ;;
            --dry-run)
                DRY_RUN=true
                shift
                ;;
            -h | --help)
                usage 0
                ;;
            *)
                echo "Error: unknown option: $1" >&2
                usage
                ;;
        esac
    done
}

assign_flag_value() {
    case "$1" in
        --steps) STEPS="$2" ;;
        --aws-issuer-url) AWS_ISSUER_URL="$2" ;;
        --aws-role-arn) AWS_ROLE_ARN="$2" ;;
        --aws-role-name) AWS_ROLE_NAME="$2" ;;
        --connection-name) CONNECTION_NAME="$2" ;;
        --azure-tenant-id) AZURE_TENANT_ID_FLAG="$2" ;;
        --telemetry-app-id) TELEMETRY_APP_ID_FLAG="$2" ;;
        --config-app-id) CONFIG_APP_ID_FLAG="$2" ;;
        --aws-region) AWS_REGION="$2" ;;
    esac
}

validate_inputs() {
    validate_steps
    validate_aws_region
    validate_aws_identity_inputs
    validate_azure_identity_alone_inputs
    validate_connectors_inputs
    validate_connectors_alone_inputs
}

validate_aws_region() {
    if [[ -z "${AWS_REGION}" ]]; then
        echo "Error: --aws-region is required." >&2
        usage
    fi
    if [[ ! "${AWS_REGION}" =~ ^[a-z]{2}-[a-z]+-[0-9]+$ ]]; then
        die_usage "--aws-region must be an AWS commercial region such as us-east-1."
    fi
}

validate_aws_identity_inputs() {
    if has_step aws-identity || has_step connectors; then
        [[ -n "${AWS_ROLE_NAME}" ]] ||
            die_usage "--aws-role-name is required because --steps includes aws-identity or connectors."
        [[ "${AWS_ROLE_NAME}" =~ ^[A-Za-z0-9+=,.@_-]{1,64}$ ]] ||
            die_usage "--aws-role-name must be a valid IAM role name (A-Z a-z 0-9 + = , . @ _ -, up to 64 chars)."
    fi
}

validate_azure_identity_alone_inputs() {
    if has_step azure-identity && ! has_step aws-identity; then
        if [[ -z "${AWS_ISSUER_URL}" || -z "${AWS_ROLE_ARN}" ]]; then
            echo "Error: --aws-issuer-url and --aws-role-arn are required because --steps includes azure-identity without aws-identity." >&2
            usage
        fi

        if [[ ! "${AWS_ISSUER_URL}" =~ ^https://[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\.tokens\.sts\.global\.api\.aws$ ]]; then
            die_usage "--aws-issuer-url must be an AWS IAM Outbound Identity Federation URL."
        fi
        AWS_ISSUER_URL=$(echo "${AWS_ISSUER_URL}" | tr '[:upper:]' '[:lower:]')

        if [[ ! "${AWS_ROLE_ARN}" =~ ^arn:aws:iam::[0-9]{12}:role/[A-Za-z0-9+=,.@_/-]+$ || ${#AWS_ROLE_ARN} -gt 2048 ]]; then
            die_usage "--aws-role-arn must be a valid commercial-partition IAM role ARN."
        fi

        if [[ "${AWS_ROLE_ARN}" =~ ^arn:aws:iam::([0-9]{12}): ]]; then
            AWS_ACCOUNT_ID="${BASH_REMATCH[1]}"
        else
            die_usage "Could not derive the AWS account id from --aws-role-arn."
        fi
    fi
}

validate_connectors_inputs() {
    if has_step connectors; then
        [[ -n "${CONNECTION_NAME}" ]] ||
            die_usage "--connection-name is required because --steps includes connectors."
        if [[ "${CONNECTION_NAME}" =~ [[:space:]] ]]; then
            die_usage "--connection-name must not contain whitespace."
        fi
        if [[ "${CONNECTION_NAME}" =~ [[:cntrl:]] ]]; then
            die_usage "--connection-name must not contain control characters."
        fi
        if [[ "${#CONNECTION_NAME}" -gt 256 ]]; then
            die_usage "--connection-name must be 256 characters or fewer."
        fi
    fi
}

validate_connectors_alone_inputs() {
    if has_step connectors && ! has_step azure-identity; then
        if [[ -z "${AZURE_TENANT_ID_FLAG}" || -z "${TELEMETRY_APP_ID_FLAG}" ]]; then
            echo "Error: --azure-tenant-id and --telemetry-app-id are required because --steps includes connectors without azure-identity." >&2
            usage
        fi
        is_guid "${AZURE_TENANT_ID_FLAG}" || die_usage "--azure-tenant-id must be a GUID."
        is_guid "${TELEMETRY_APP_ID_FLAG}" || die_usage "--telemetry-app-id must be a GUID."
        TENANT_ID=$(echo "${AZURE_TENANT_ID_FLAG}" | tr '[:upper:]' '[:lower:]')
        APP_ID="${TELEMETRY_APP_ID_FLAG}"

        if [[ "${TELEMETRY_ONLY}" == false ]]; then
            [[ -n "${CONFIG_APP_ID_FLAG}" ]] ||
                die_usage "--config-app-id is required because --steps includes connectors without azure-identity, unless --telemetry-only."
            is_guid "${CONFIG_APP_ID_FLAG}" || die_usage "--config-app-id must be a GUID."
            CONFIG_APP_ID="${CONFIG_APP_ID_FLAG}"
        fi
    fi
}

check_tools() {
    if command -v jq >/dev/null 2>&1; then
        JQ_VERSION=$(jq --version 2>/dev/null || true)
        JQ_VERSION="${JQ_VERSION#jq-}"
        if [[ -z "${JQ_VERSION}" ]] || ! version_at_least "${JQ_VERSION}" "${MIN_JQ_VERSION}"; then
            HAVE_JQ=false
            add_issue command "jq ${JQ_VERSION:-unknown} detected; >= ${MIN_JQ_VERSION} is required. Upgrade jq, then re-run."
        fi
    else
        HAVE_JQ=false
        add_issue command "jq not found. Install jq, then re-run."
    fi

    if has_step aws-identity || has_step connectors; then
        if command -v aws >/dev/null 2>&1; then
            if has_step connectors && [[ "${HAVE_JQ}" == true ]]; then
                local oa_missing=()
                local oa_cmd
                for oa_cmd in create-connector list-connectors get-connector list-resources-by-connector; do
                    aws observabilityadmin "${oa_cmd}" help >/dev/null 2>&1 || oa_missing+=("${oa_cmd}")
                done
                [[ ${#oa_missing[@]} -eq 0 ]] ||
                    add_issue command "AWS CLI needs to be updated — see https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html. Update it, then run this command again. Nothing was changed."
            fi
        else
            HAVE_AWS_CLI=false
            add_issue command "aws CLI not found. Install it, then re-run."
        fi
    fi

    if has_step azure-identity; then
        if command -v az >/dev/null 2>&1; then
            az bicep version >/dev/null 2>&1 ||
                add_issue command "The az bicep extension is required for ingestion setup. Run 'az bicep install', then re-run."
            if [[ "${HAVE_JQ}" == true ]]; then
                AZ_VERSION=$(az version -o json 2>/dev/null | jq -r '."azure-cli" // empty' || true)
                if [[ -z "${AZ_VERSION}" ]] || ! version_at_least "${AZ_VERSION}" "${MIN_AZ_VERSION}"; then
                    HAVE_AZ_CLI=false
                    add_issue command "Azure CLI ${AZ_VERSION:-unknown} detected; >= ${MIN_AZ_VERSION} is required."
                fi
            fi
        else
            HAVE_AZ_CLI=false
            add_issue command "az CLI not found. Install it, then re-run."
        fi
    fi
}

read_context() {
    if has_step azure-identity && [[ "${HAVE_AZ_CLI}" == true && "${HAVE_JQ}" == true ]]; then
        ACCOUNT_JSON=$(az account show --output json 2>/dev/null || true)
        if [[ -z "${ACCOUNT_JSON}" ]]; then
            add_issue azure "Not logged in to Azure. Run 'az login' against the Azure tenant you want to onboard, then re-run this script."
            HAVE_AZURE_CONTEXT=false
        else
            TENANT_ID=$(echo "${ACCOUNT_JSON}" | jq -r '.tenantId // empty' | tr '[:upper:]' '[:lower:]')
            if ! is_guid "${TENANT_ID}"; then
                add_issue azure "Could not determine the Azure tenant from 'az account show'. Run 'az login' and select a subscription first."
                HAVE_AZURE_CONTEXT=false
            else
                TENANT_NAME=$(echo "${ACCOUNT_JSON}" | jq -r '.tenantDisplayName // empty')
                TENANT_DOMAIN=$(echo "${ACCOUNT_JSON}" | jq -r '.tenantDefaultDomain // empty')
                if [[ -z "${TENANT_NAME}" || -z "${TENANT_DOMAIN}" ]]; then
                    ORG_JSON=$(az rest --method get \
                        --url 'https://graph.microsoft.com/v1.0/organization?$select=displayName,verifiedDomains' \
                        --output json 2>/dev/null || true)
                    if [[ -n "${ORG_JSON}" ]]; then
                        [[ -n "${TENANT_NAME}" ]] || TENANT_NAME=$(echo "${ORG_JSON}" | jq -r '.value[0].displayName // empty')
                        [[ -n "${TENANT_DOMAIN}" ]] || TENANT_DOMAIN=$(echo "${ORG_JSON}" |
                            jq -r '[.value[0].verifiedDomains[]? | select(.isDefault)][0].name // empty')
                    fi
                fi

                MANAGEMENT_GROUP_SCOPE="/providers/Microsoft.Management/managementGroups/${TENANT_ID}"
            fi
        fi
    fi

    if (has_step aws-identity || has_step connectors) && [[ "${HAVE_AWS_CLI}" == true && "${HAVE_JQ}" == true ]]; then
        local caller_json
        local error_file
        local error_output
        error_file=$(mktemp "${TMPDIR:-/tmp}/cloudwatch-azure-cli-error.XXXXXX") ||
            die "Failed to create a temporary file to read the signed-in AWS account."
        if caller_json=$(aws sts get-caller-identity --output json 2>"${error_file}"); then
            rm -f -- "${error_file}"
        else
            error_output=$(cat -- "${error_file}")
            rm -f -- "${error_file}"
            add_issue aws "Failed to determine the signed-in AWS account: ${error_output//$'\n'/ } Run 'aws configure' or check your credentials, then re-run this script."
            HAVE_AWS_CONTEXT=false
            caller_json=""
        fi
        if [[ -n "${caller_json}" ]]; then
            AWS_ACCOUNT_ID=$(echo "${caller_json}" | jq -r '.Account')
            CALLER_ARN=$(echo "${caller_json}" | jq -r '.Arn')
            if [[ ! "${AWS_ACCOUNT_ID}" =~ ^[0-9]{12}$ ]]; then
                add_issue aws "aws sts get-caller-identity did not return a 12-digit account id."
                HAVE_AWS_CONTEXT=false
            else
                [[ -n "${AWS_ROLE_ARN}" ]] || AWS_ROLE_ARN="arn:aws:iam::${AWS_ACCOUNT_ID}:role/${AWS_ROLE_NAME}"
            fi
        fi
    fi
}

check_permissions() {
    step_progress "Checking permissions"

    if has_step azure-identity && [[ "${HAVE_AZ_CLI}" == true && "${HAVE_AZURE_CONTEXT}" == true && "${HAVE_JQ}" == true ]]; then
        local mg_error
        if ! mg_error=$(az account management-group show --name "${TENANT_ID}" --output none 2>&1); then
            add_issue azure "Tenant root management group ${TENANT_ID} is unavailable to the active principal: ${mg_error//$'\n'/ } Run 'az login --tenant ${TENANT_ID}' as a principal with access to it, then re-run."
        elif read_root_permissions; then
            permission_allowed "${PERMISSIONS_JSON}" "Microsoft.Authorization/roleAssignments/write" ||
                note_missing_permission "Microsoft.Authorization/roleAssignments/write" "the tenant root management group ${TENANT_ID}"

            log "Tenant ${TENANT_ID} is reachable; checking the remaining Azure permissions required for ingestion setup."
            check_azure_app_registration_permission
            check_forward_root_permissions
            [[ "${TELEMETRY_ONLY}" == true ]] || check_forward_config_permissions
            report_missing_permissions
        fi
    fi

    if (has_step aws-identity || has_step connectors) && [[ "${HAVE_AWS_CLI}" == true && "${HAVE_AWS_CONTEXT}" == true && "${HAVE_JQ}" == true ]]; then
        check_aws_permissions
    fi

    [[ -z "${AWS_ACCOUNT_ID:-}" ]] || log "AWS account: ${AWS_ACCOUNT_ID}, region ${AWS_REGION}."
}

effective_permissions() {
    local scope="$1"
    local url="https://management.azure.com${scope}/providers/Microsoft.Authorization/permissions?api-version=2022-04-01"
    local page
    local pages=""
    local error_file
    local error_output
    local status=0

    while [[ -n "${url}" ]]; do
        error_file=$(mktemp "${TMPDIR:-/tmp}/cloudwatch-azure-cli-error.XXXXXX") || {
            echo "Failed to create a temporary file to read permissions at ${scope}." >&2
            return 1
        }
        page=$(az rest --method get --url "${url}" --output json 2>"${error_file}") || status=$?
        error_output=$(cat -- "${error_file}")
        rm -f -- "${error_file}"
        if [[ ${status} -ne 0 ]]; then
            echo "${error_output}" >&2
            return 1
        fi
        url=$(printf '%s' "${page}" |
            jq -er 'if (.value | type) == "array" then .nextLink // "" else error end' 2>/dev/null) || {
            echo "Azure returned an invalid permissions list at ${scope}." >&2
            return 1
        }
        pages+="${page}"$'\n'
    done
    printf '%s' "${pages}" | jq -cs '{value:[.[].value[]]}'
}

read_root_permissions() {
    local error_file
    local error_output

    error_file=$(mktemp "${TMPDIR:-/tmp}/cloudwatch-azure-cli-error.XXXXXX") ||
        die "Failed to create a temporary file to read the tenant-root permissions."
    if PERMISSIONS_JSON=$(effective_permissions "${MANAGEMENT_GROUP_SCOPE}" 2>"${error_file}"); then
        rm -f -- "${error_file}"
    else
        error_output=$(cat -- "${error_file}")
        rm -f -- "${error_file}"
        if is_authorization_failure "${error_output}"; then
            add_issue azure "The active principal cannot read its own permissions at the tenant root management group ${TENANT_ID} (authorization failed): ${error_output//$'\n'/ }"
        else
            add_issue azure "Failed to read the active principal's permissions at the tenant root management group ${TENANT_ID}: ${error_output//$'\n'/ }"
        fi
        return 1
    fi
    # Slurped because jq 1.6 exits 0 under -e for empty input.
    if ! jq -se 'length == 1 and (.[0].value | type == "array")' >/dev/null 2>&1 <<< "${PERMISSIONS_JSON}"; then
        add_issue azure "The permissions read at the tenant root management group ${TENANT_ID} returned no permissions list."
        return 1
    fi
    return 0
}

MISSING_PERMISSION_ROLES=(
    "Owner, or Contributor"
    "Owner, or User Access Administrator"
    "Owner, or Resource Policy Contributor"
    "The Microsoft Entra role Security Administrator or Global Administrator"
    "A Microsoft Entra role that can read diagnostic settings, such as Security Reader or Global Reader")
MISSING_PERMISSION_KEYS=()
MISSING_PERMISSION_ACTIONS=()

note_missing_permission() {
    local action="$1"
    local place="$2"
    local bucket key i

    case "$(printf '%s' "${action}" | tr '[:upper:]' '[:lower:]')" in
        microsoft.aadiam/*/read) bucket=4 ;;
        microsoft.aadiam/*) bucket=3 ;;
        microsoft.authorization/*/read) bucket=0 ;;
        microsoft.authorization/policyassignments/*|microsoft.authorization/policydefinitions/*) bucket=2 ;;
        microsoft.authorization/*) bucket=1 ;;
        *) bucket=0 ;;
    esac
    key="${bucket}:${place}"

    for ((i = 0; i < ${#MISSING_PERMISSION_KEYS[@]}; i++)); do
        if [[ "${MISSING_PERMISSION_KEYS[i]}" == "${key}" ]]; then
            MISSING_PERMISSION_ACTIONS[i]+=$'\x1f'"${action}"
            return
        fi
    done
    MISSING_PERMISSION_KEYS+=("${key}")
    MISSING_PERMISSION_ACTIONS+=("${action}")
}

format_missing_action_list() {
    local -a actions
    local n i out=""

    IFS=$'\x1f' read -ra actions <<< "$1"
    n=${#actions[@]}
    for ((i = 0; i < n; i++)); do
        if ((i == 0)); then
            out="'${actions[i]}'"
        elif ((i == n - 1)); then
            if ((n == 2)); then
                out+=" and '${actions[i]}'"
            else
                out+=", and '${actions[i]}'"
            fi
        else
            out+=", '${actions[i]}'"
        fi
    done
    printf '%s' "${out}"
}

report_missing_permissions() {
    local i role_idx place
    local -a bucket_lines
    local report=""

    bucket_lines=()
    for ((i = 0; i < ${#MISSING_PERMISSION_ROLES[@]}; i++)); do
        bucket_lines[i]=""
    done
    for ((i = 0; i < ${#MISSING_PERMISSION_KEYS[@]}; i++)); do
        role_idx="${MISSING_PERMISSION_KEYS[i]%%:*}"
        place="${MISSING_PERMISSION_KEYS[i]#*:}"
        bucket_lines[role_idx]+=$'\n'"    Missing $(format_missing_action_list "${MISSING_PERMISSION_ACTIONS[i]}") at ${place}."
    done

    for ((i = 0; i < ${#MISSING_PERMISSION_ROLES[@]}; i++)); do
        [[ -z "${bucket_lines[i]}" ]] ||
            report+=$'\n'"  ${MISSING_PERMISSION_ROLES[i]}, or a custom role with these actions:${bucket_lines[i]}"
    done
    [[ -z "${report}" ]] ||
        add_issue azure "The signed-in account is missing Azure permissions required for ingestion setup.${report}"
}

check_forward_root_permissions() {
    local action
    local place="the tenant root management group ${TENANT_ID}"
    for action in \
        "Microsoft.Resources/deployments/validate/action" \
        "Microsoft.Resources/deployments/write" \
        "Microsoft.Resources/deployments/read" \
        "Microsoft.Authorization/policyAssignments/write" \
        "Microsoft.PolicyInsights/remediations/read" \
        "Microsoft.PolicyInsights/remediations/write" \
        "Microsoft.Resources/subscriptions/read" \
        "Microsoft.Authorization/policyDefinitions/read" \
        "Microsoft.Authorization/policyAssignments/read"; do
        permission_allowed "${PERMISSIONS_JSON}" "${action}" || note_missing_permission "${action}" "${place}"
    done
}

check_forward_config_permissions() {
    local action
    local place="the tenant root management group ${TENANT_ID}"

    for action in \
        "Microsoft.Authorization/roleAssignments/read" \
        "Microsoft.EventHub/namespaces/read" \
        "Microsoft.Authorization/roleDefinitions/read" \
        "Microsoft.Insights/diagnosticSettings/read" \
        "Microsoft.Authorization/roleDefinitions/write" \
        "Microsoft.Authorization/policyDefinitions/write"; do
        permission_allowed "${PERMISSIONS_JSON}" "${action}" || note_missing_permission "${action}" "${place}"
    done

    check_forward_entra_permissions
}

check_forward_entra_permissions() {
    local entra_permissions action error_file error_output
    local place="Microsoft Entra ID"

    error_file=$(mktemp "${TMPDIR:-/tmp}/cloudwatch-azure-cli-error.XXXXXX") ||
        die "Failed to create a temporary file to read permissions at Microsoft Entra ID."
    if entra_permissions=$(effective_permissions "/providers/microsoft.aadiam" 2>"${error_file}"); then
        rm -f -- "${error_file}"
    else
        error_output=$(cat -- "${error_file}")
        rm -f -- "${error_file}"
        warn "Could not read effective permissions at Microsoft Entra ID (/providers/microsoft.aadiam); continuing. If the next setup script fails, check microsoft.aadiam/diagnosticSettings/read and /write there. ${error_output//$'\n'/ }"
        return
    fi
    for action in "microsoft.aadiam/diagnosticSettings/read" "microsoft.aadiam/diagnosticSettings/write"; do
        permission_allowed "${entra_permissions}" "${action}" || note_missing_permission "${action}" "${place}"
    done
}

all_actions_allowed() {
    local result="$1"
    shift
    local names_json
    names_json=$(printf '%s\n' "$@" | jq -R . | jq -sc .)
    echo "${result}" | jq -e --argjson names "${names_json}" \
        '[.EvaluationResults[]? | select(.EvalActionName | IN($names[])) | select(.EvalDecision != "allowed")] | length == 0' >/dev/null
}

check_aws_permissions() {
    local aws_identity_actions=()
    local connectors_actions=()
    local actions=()
    local result

    if has_step aws-identity; then
        aws_identity_actions=(iam:GetRole iam:CreateRole iam:UpdateAssumeRolePolicy iam:PutRolePolicy \
            iam:GetRolePolicy iam:GetOutboundWebIdentityFederationInfo iam:EnableOutboundWebIdentityFederation)
        actions+=("${aws_identity_actions[@]}")
    fi
    if has_step connectors; then
        connectors_actions=(observabilityadmin:CreateConnector observabilityadmin:ListConnectors \
            observabilityadmin:GetConnector observabilityadmin:ListResourcesByConnector)
        if [[ "${TELEMETRY_ONLY}" == false ]]; then
            connectors_actions+=(config:PutConnector config:ListConnectors config:GetConnector \
                config:ListTagsForResource config:TagResource iam:CreateServiceLinkedRole)
        fi
        actions+=("${connectors_actions[@]}")
    fi

    [[ -n "${CALLER_ARN:-}" ]] || return 0
    result=$(aws iam simulate-principal-policy \
        --policy-source-arn "${CALLER_ARN}" \
        --action-names "${actions[@]}" \
        --output json 2>/dev/null) || return 0

    if [[ ${#aws_identity_actions[@]} -gt 0 ]] && ! all_actions_allowed "${result}" "${aws_identity_actions[@]}"; then
        warn "Some AWS IAM permissions for aws-identity may be missing; continuing. If the connector role step fails, check iam:CreateRole, PutRolePolicy, UpdateAssumeRolePolicy, and EnableOutboundWebIdentityFederation."
    fi
    if [[ ${#connectors_actions[@]} -gt 0 ]] && ! all_actions_allowed "${result}" "${connectors_actions[@]}"; then
        warn "Some AWS IAM permissions for connectors may be missing; continuing. If the connectors step fails, check observabilityadmin:CreateConnector/ListConnectors/GetConnector/ListResourcesByConnector and, unless --telemetry-only, config:PutConnector/ListConnectors/GetConnector/ListTagsForResource/TagResource and iam:CreateServiceLinkedRole."
    fi
}

check_azure_app_registration_permission() {
    local roles_json
    local policy_json
    local roles_ok=false
    local policy_ok=false
    local has_admin_role=false
    local users_can_register=false

    roles_json=$(az rest --method get \
        --url 'https://graph.microsoft.com/v1.0/me/transitiveMemberOf?$select=displayName,roleTemplateId' \
        --output json 2>/dev/null) && roles_ok=true || roles_json=""
    policy_json=$(az rest --method get \
        --url 'https://graph.microsoft.com/v1.0/policies/authorizationPolicy' \
        --output json 2>/dev/null) && policy_ok=true || policy_json=""

    if [[ "${roles_ok}" == false && "${policy_ok}" == false ]]; then
        log "Could not verify Azure app registration permissions, continuing."
        return 0
    fi

    if [[ "${roles_ok}" == true ]] && echo "${roles_json}" | jq -e \
        '[.value[]? | select(.roleTemplateId == "158c047a-c907-4556-b7ef-446551a6b5f7"
            or .roleTemplateId == "9b895d92-2cd3-44c7-9d02-a6ac2d5ea5c3"
            or .roleTemplateId == "62e90394-69f5-4237-9190-012177145e10")] | length > 0' \
        >/dev/null; then
        has_admin_role=true
    fi

    if [[ "${policy_ok}" == true ]] && echo "${policy_json}" | jq -e \
        '.defaultUserRolePermissions.allowedToCreateApps == true' >/dev/null; then
        users_can_register=true
    fi

    if [[ "${has_admin_role}" == true || "${users_can_register}" == true ]]; then
        return 0
    fi

    if [[ "${roles_ok}" == true && "${policy_ok}" == true ]]; then
        add_issue azure "The signed-in principal cannot register Microsoft Entra applications in tenant ${TENANT_ID}: it does not hold Cloud Application Administrator, Application Administrator, or Global Administrator, and the tenant's default user policy does not allow users to register applications. Sign in as a principal with one of those roles, or have a tenant administrator allow users to register applications, then re-run."
        return 0
    fi
    warn "Could not fully verify Azure app registration permissions for the signed-in principal; continuing. If the azure-identity step fails, Cloud Application Administrator, Application Administrator, or a tenant policy allowing users to register applications is needed."
}

plan_azure_identity() {
    plan_telemetry_identity_names
    plan_config_identity_names
    detect_config_connector_owner
}

plan_telemetry_identity_names() {
    APP_NAME="AWS CloudWatch Ingestion ${AWS_ACCOUNT_ID}-${AWS_REGION}"

    TELEMETRY_ACCOUNT_TAG="aws-cloudwatch-ingestion-account=${AWS_ACCOUNT_ID}"
    TELEMETRY_REGION_TAG="aws-cloudwatch-ingestion-region=${AWS_REGION}"
    TELEMETRY_TAGS=$(jq -cn --arg a "${TELEMETRY_ACCOUNT_TAG}" --arg r "${TELEMETRY_REGION_TAG}" '[$a, $r]')
}

plan_config_identity_names() {
    CONFIG_APP_NAME="AWS Config ${AWS_ACCOUNT_ID}-${AWS_REGION}"
    CONFIG_APP_SLUG="aws-config-${AWS_ACCOUNT_ID}-${AWS_REGION}"
    CONFIG_IDENTIFIER_URI="api://${TENANT_ID}/${CONFIG_APP_SLUG}"
    CONFIG_ACCOUNT_TAG="aws-config-account=${AWS_ACCOUNT_ID}"
    CONFIG_REGION_TAG="aws-config-region=${AWS_REGION}"
    CONFIG_TAGS=$(jq -cn --arg a "${CONFIG_ACCOUNT_TAG}" --arg r "${CONFIG_REGION_TAG}" '[$a, $r]')

    CONFIG_SLR_ARN="arn:aws:iam::${AWS_ACCOUNT_ID}:role/aws-service-role/thirdparty.config.amazonaws.com/AWSServiceRoleForConfigThirdParty"
}

detect_config_connector_owner() {
    CONFIG_CONNECTOR_OWNER_ARN=""
    CONFIG_CONNECTOR_OWNER_CLIENT_ID=""
    if [[ "${TELEMETRY_ONLY}" == false ]] && has_step connectors; then
        local owner
        owner=$(find_config_connector_owner)
        if [[ -n "${owner}" ]]; then
            read -r CONFIG_CONNECTOR_OWNER_ARN CONFIG_CONNECTOR_OWNER_CLIENT_ID <<< "${owner}"
        fi

        if [[ -n "${CONFIG_CONNECTOR_OWNER_ARN}" ]]; then
            local self_tagged_app_id
            self_tagged_app_id=$(find_existing_app_by_tag "${CONFIG_TAGS}" | tr '[:upper:]' '[:lower:]')
            if [[ -n "${self_tagged_app_id}" &&
                "$(echo "${CONFIG_CONNECTOR_OWNER_CLIENT_ID}" | tr '[:upper:]' '[:lower:]')" == "${self_tagged_app_id}" ]]; then
                CONFIG_CONNECTOR_OWNER_ARN=""
                CONFIG_CONNECTOR_OWNER_CLIENT_ID=""
            fi
        fi
    fi
}

build_connector_trust_statement() {
    jq -cn \
        --arg sid "${CONNECTOR_TRUST_SID}" \
        --arg principal "${CONNECTOR_SERVICE_PRINCIPAL}" \
        --arg account "${AWS_ACCOUNT_ID}" \
        --arg arn "arn:aws:observabilityadmin:${AWS_REGION}:${AWS_ACCOUNT_ID}:connector/*" \
        '{
            Sid: $sid,
            Effect: "Allow",
            Principal: {Service: $principal},
            Action: "sts:AssumeRole",
            Condition: {StringEquals: {"aws:SourceAccount": $account}, ArnLike: {"aws:SourceArn": $arn}}
        }'
}

check_outbound_federation() {
    local info

    info=$(aws iam get-outbound-web-identity-federation-info --output json 2>/dev/null) || info=""
    if [[ -n "${info}" ]] && echo "${info}" | jq -e '.JwtVendingEnabled == true' >/dev/null 2>&1; then
        AWS_ISSUER_URL=$(echo "${info}" | jq -r '.IssuerIdentifier' | tr '[:upper:]' '[:lower:]')
        FEDERATION_STATUS="existing"
    elif [[ "${DRY_RUN}" == true ]]; then
        AWS_ISSUER_URL="<dry-run-issuer-url>"
        FEDERATION_STATUS="create"
    else
        FEDERATION_STATUS="create"
    fi
}

check_connector_role() {
    local role_json
    local trust_doc
    local existing_connector
    local existing_pipeline

    role_json=$(read_optional_aws_json "connector role ${AWS_ROLE_NAME}" \
        aws iam get-role --role-name "${AWS_ROLE_NAME}" --output json) || exit 1
    if [[ -z "${role_json}" ]]; then
        ROLE_STATUS="create"
        return 0
    fi
    validate_connector_role_path "${role_json}"

    trust_doc=$(echo "${role_json}" | jq -c '.Role.AssumeRolePolicyDocument')
    EXISTING_TRUST_DOC="${trust_doc}"
    check_connector_trust_statements "${trust_doc}"
    existing_connector="${EXISTING_CONNECTOR_STATEMENT}"
    existing_pipeline="${EXISTING_PIPELINE_STATEMENT}"

    check_connector_role_policy
    decide_connector_role_status "${existing_connector}" "${existing_pipeline}" && return 0

    build_connector_role_missing_list "${existing_connector}" "${existing_pipeline}"

    [[ "${DRY_RUN}" == true ]] && return 0 || true

    prompt_connector_role_update "${CONNECTOR_ROLE_MISSING[@]}"
}

validate_connector_role_path() {
    local role_json="$1"
    local path

    path=$(echo "${role_json}" | jq -r '.Role.Path')
    [[ "${path}" == "/" ]] ||
        die "An IAM role named ${AWS_ROLE_NAME} already exists at path ${path}. Choose another role name in the console."
}

check_connector_trust_statements() {
    local trust_doc="$1"

    EXISTING_CONNECTOR_STATEMENT=$(echo "${trust_doc}" | jq -c --arg sid "${CONNECTOR_TRUST_SID}" '.Statement[] | select(.Sid == $sid)')
    if [[ -n "${EXISTING_CONNECTOR_STATEMENT}" &&
        "$(echo "${EXISTING_CONNECTOR_STATEMENT}" | jq -Sc .)" != "$(echo "${CONNECTOR_TRUST_STATEMENT}" | jq -Sc .)" ]]; then
        die "Role ${AWS_ROLE_NAME} has a trust statement with Sid ${CONNECTOR_TRUST_SID} that differs from what CloudWatch needs. Remove or fix that statement, then rerun."
    fi
    EXISTING_PIPELINE_STATEMENT=$(echo "${trust_doc}" | jq -c --arg sid "${PIPELINE_TRUST_SID}" '.Statement[] | select(.Sid == $sid)')
    if [[ -n "${EXISTING_PIPELINE_STATEMENT}" &&
        "$(echo "${EXISTING_PIPELINE_STATEMENT}" | jq -Sc .)" != "$(echo "${PIPELINE_TRUST_STATEMENT}" | jq -Sc .)" ]]; then
        die "Role ${AWS_ROLE_NAME} has a trust statement with Sid ${PIPELINE_TRUST_SID} that differs from what CloudWatch needs. Remove or fix that statement, then rerun."
    fi
}

check_connector_role_policy() {
    local simulate_json

    CONNECTOR_ROLE_HAS_POLICY=false
    CONNECTOR_ROLE_POLICY_UNKNOWN=false

    if simulate_json=$(aws iam simulate-principal-policy \
        --policy-source-arn "${AWS_ROLE_ARN}" \
        --action-names sts:GetWebIdentityToken \
        --context-entries "ContextKeyName=sts:IdentityTokenAudience,ContextKeyType=string,ContextKeyValues=${AUDIENCE}" \
        --output json 2>/dev/null); then
        if echo "${simulate_json}" | jq -e \
            '[.EvaluationResults[]? | select(.EvalDecision == "allowed")] | length > 0' >/dev/null; then
            CONNECTOR_ROLE_HAS_POLICY=true
        fi
    else
        CONNECTOR_ROLE_POLICY_UNKNOWN=true
    fi
}

decide_connector_role_status() {
    local existing_connector="$1"
    local existing_pipeline="$2"

    if [[ -n "${existing_connector}" && -n "${existing_pipeline}" ]]; then
        if [[ "${CONNECTOR_ROLE_HAS_POLICY}" == true ]]; then
            ROLE_STATUS="existing"
            return 0
        fi
        if [[ "${CONNECTOR_ROLE_POLICY_UNKNOWN}" == true ]]; then
            ROLE_STATUS="update"
            return 0
        fi
    fi
    ROLE_STATUS="update"
    return 1
}

build_connector_role_missing_list() {
    local existing_connector="$1"
    local existing_pipeline="$2"

    CONNECTOR_ROLE_MISSING=()
    [[ -n "${existing_connector}" ]] || CONNECTOR_ROLE_MISSING+=("trust for ${CONNECTOR_SERVICE_PRINCIPAL}")
    [[ -n "${existing_pipeline}" ]] || CONNECTOR_ROLE_MISSING+=("trust for ${PIPELINE_SERVICE_PRINCIPAL}")
    [[ "${CONNECTOR_ROLE_HAS_POLICY}" == true || "${CONNECTOR_ROLE_POLICY_UNKNOWN}" == true ]] ||
        CONNECTOR_ROLE_MISSING+=("permission sts:GetWebIdentityToken for audience ${AUDIENCE}")
}

prompt_connector_role_update() {
    local missing=("$@")
    local item
    local reply
    local discarded

    if [[ ! -t 0 ]]; then
        die "IAM role ${AWS_ROLE_NAME} needs updating, but stdin is not a terminal so the update can't be confirmed interactively. Run this script directly in a terminal, or use --dry-run to preview the changes."
    fi

    echo "IAM role ${AWS_ROLE_NAME} already exists but is missing:" >&2
    for item in "${missing[@]}"; do
        echo "  - ${item}" >&2
    done
    echo "Add these to the role? Existing trust statements and policies are kept." >&2

    while IFS= read -r -t 1 discarded; do :; done

    while :; do
        printf '  [u] Update the role   [e] Exit without changes ' >&2
        read -r reply || die "Aborted."
        case "${reply}" in
            [Uu]) return 0 ;;
            [Ee] | "")
                die "IAM role ${AWS_ROLE_NAME} is still missing $(printf '%s\n' "${missing[@]}" | jq -Rsr 'split("\n") | map(select(length > 0)) | join(", ")')." \
                    "Add the permissions listed above to the role, or rerun and choose Update."
                ;;
            *) echo "Please enter 'u' to update or 'e' to exit." >&2 ;;
        esac
    done
}

compute_expected_role_trust() {
    CONNECTOR_TRUST_SID=$(trust_statement_sid "CloudWatchAzureConnector" "${AWS_REGION}" "${CONNECTOR_SERVICE_PRINCIPAL}")
    PIPELINE_TRUST_SID=$(trust_statement_sid "CloudWatchAzureConnectorPipeline" "${AWS_REGION}" "${PIPELINE_SERVICE_PRINCIPAL}")
    CONNECTOR_TRUST_STATEMENT=$(build_connector_trust_statement)
    PIPELINE_TRUST_STATEMENT=$(jq -cn \
        --arg sid "${PIPELINE_TRUST_SID}" --arg principal "${PIPELINE_SERVICE_PRINCIPAL}" \
        '{Sid: $sid, Effect: "Allow", Principal: {Service: $principal}, Action: "sts:AssumeRole"}')
}

plan_aws_identity() {
    compute_expected_role_trust
    TOKEN_EXCHANGE_POLICY_DOCUMENT=$(jq -cn --arg audience "${AUDIENCE}" '
        {Version: "2012-10-17", Statement: [{
            Effect: "Allow", Action: "sts:GetWebIdentityToken", Resource: "*",
            Condition: {
                "ForAllValues:StringEquals": {"sts:IdentityTokenAudience": $audience},
                "Null": {"sts:IdentityTokenAudience": "false"}
            }
        }]}')

    check_outbound_federation
    check_connector_role
}

apply_aws_identity() {
    step_progress "AWS outbound identity federation"
    if [[ "${FEDERATION_STATUS}" == "existing" ]]; then
        log "AWS outbound identity federation: enabled (existing)."
    elif [[ "${DRY_RUN}" == true ]]; then
        log "Would enable AWS outbound identity federation."
    else
        AWS_ISSUER_URL=$(aws iam enable-outbound-web-identity-federation --query IssuerIdentifier --output text) ||
            die "Failed to enable AWS outbound identity federation."
        AWS_ISSUER_URL=$(echo "${AWS_ISSUER_URL}" | tr '[:upper:]' '[:lower:]')
        log "AWS outbound identity federation: enabled (created)."
    fi

    step_progress "AWS connector role"
    case "${ROLE_STATUS}" in
        create)
            if [[ "${DRY_RUN}" == true ]]; then
                log "Would create IAM role ${AWS_ROLE_NAME}."
            else
                local trust_policy
                trust_policy=$(jq -cn --argjson connector "${CONNECTOR_TRUST_STATEMENT}" --argjson pipeline "${PIPELINE_TRUST_STATEMENT}" \
                    '{Version: "2012-10-17", Statement: [$connector, $pipeline]}')
                aws iam create-role --role-name "${AWS_ROLE_NAME}" \
                    --assume-role-policy-document "${trust_policy}" >/dev/null ||
                    die "Failed to create IAM role ${AWS_ROLE_NAME}."
                aws iam put-role-policy --role-name "${AWS_ROLE_NAME}" \
                    --policy-name "${TOKEN_EXCHANGE_POLICY_NAME}" \
                    --policy-document "${TOKEN_EXCHANGE_POLICY_DOCUMENT}" >/dev/null ||
                    die "Failed to attach the ${TOKEN_EXCHANGE_POLICY_NAME} policy to IAM role ${AWS_ROLE_NAME}."
                log "Connector role ${AWS_ROLE_NAME} (created)."
            fi
            ;;
        update)
            if [[ "${DRY_RUN}" == true ]]; then
                log "Would update IAM role ${AWS_ROLE_NAME} with the missing trust statements/policy."
            else
                local merged_trust
                merged_trust=$(jq -c \
                    --argjson connector "${CONNECTOR_TRUST_STATEMENT}" \
                    --argjson pipeline "${PIPELINE_TRUST_STATEMENT}" \
                    '.Statement |= (map(select(.Sid != $connector.Sid and .Sid != $pipeline.Sid)) + [$connector, $pipeline])' \
                    <<< "${EXISTING_TRUST_DOC}")
                aws iam update-assume-role-policy --role-name "${AWS_ROLE_NAME}" \
                    --policy-document "${merged_trust}" >/dev/null ||
                    die "Failed to update the trust policy for IAM role ${AWS_ROLE_NAME}."
                aws iam put-role-policy --role-name "${AWS_ROLE_NAME}" \
                    --policy-name "${TOKEN_EXCHANGE_POLICY_NAME}" \
                    --policy-document "${TOKEN_EXCHANGE_POLICY_DOCUMENT}" >/dev/null ||
                    die "Failed to attach the ${TOKEN_EXCHANGE_POLICY_NAME} policy to IAM role ${AWS_ROLE_NAME}."
                log "Connector role ${AWS_ROLE_NAME} (updated)."
            fi
            ;;
        existing)
            log "Connector role ${AWS_ROLE_NAME} (existing, permissions verified)."
            ;;
    esac
}

oa() {
    aws observabilityadmin "$@" --region "${AWS_REGION}"
}

oa_connector_configuration() {
    jq -cn --arg tenant "${TENANT_ID}" --arg client "$1" \
        '{Azure: {TenantIdentifier: $tenant, ClientIdentifier: $client}}'
}

config_connector_configuration() {
    jq -cn --arg tenant "${TENANT_ID}" --arg client "$1" \
        '{azure: {tenantIdentifier: $tenant, clientIdentifier: $client}}'
}

try_create_connector() {
    local label="$1"
    local output
    local error_file
    local error_output
    local status=0
    shift

    error_file=$(mktemp "${TMPDIR:-/tmp}/cloudwatch-azure-cli-error.XXXXXX") ||
        die "Failed to create a temporary file to inspect ${label}."
    output=$("$@" 2>"${error_file}") || status=$?
    error_output=$(cat -- "${error_file}")
    rm -f -- "${error_file}"

    if [[ ${status} -eq 0 ]]; then
        printf '%s' "${output}"
    elif grep -Eqi 'ConflictException' <<< "${error_output}"; then
        return 0
    else
        die "Failed to create ${label}." "" "${error_output}"
    fi
}

ensure_cloudwatch_connector() {
    local name="$1"
    local client="$2"
    local config

    config=$(oa_connector_configuration "${client}")

    if [[ "${DRY_RUN}" == true ]]; then
        log "Would create or reuse the CloudWatch connector '${name}'."
        CLOUDWATCH_CONNECTOR_ARN="<dry-run-connector-arn>"
        CLOUDWATCH_CONNECTOR_STATUS_FINAL="create"
        return 0
    fi

    try_create_cloudwatch_connector "${name}" "${client}" "${config}"
    if [[ "${CLOUDWATCH_CONNECTOR_CREATED}" == true ]]; then
        return 0
    fi

    find_cloudwatch_connector_matches "${name}"
    reuse_or_reject_cloudwatch_connector "${name}" "${client}"
}

try_create_cloudwatch_connector() {
    local name="$1"
    local client="$2"
    local config="$3"
    local result

    CLOUDWATCH_CONNECTOR_CREATED=false
    result=$(try_create_connector "CloudWatch connector '${name}'" \
        oa create-connector --connector-configuration "${config}" --role-arn "${AWS_ROLE_ARN}" \
        --name "${name}" --output json)
    if [[ -n "${result}" ]]; then
        CLOUDWATCH_CONNECTOR_ARN=$(echo "${result}" | jq -r '.Connector.Arn')
        CLOUDWATCH_CONNECTOR_STATUS_FINAL="create"
        CLOUDWATCH_CONNECTOR_CREATED=true
        log "CloudWatch connector '${name}' (created)."
    fi
}

find_cloudwatch_connector_matches() {
    local name="$1"
    local next_token=""
    local page
    local summaries
    local summary

    MATCH_BY_TENANT_ARN=""
    MATCH_BY_TENANT_NAME=""
    MATCH_BY_TENANT_CLIENT=""
    MATCH_BY_TENANT_ROLE_ARN=""
    MATCH_BY_NAME_ARN=""

    while :; do
        if [[ -n "${next_token}" ]]; then
            page=$(oa list-connectors --next-token "${next_token}" --output json) ||
                die "Failed to list CloudWatch connectors."
        else
            page=$(oa list-connectors --output json) || die "Failed to list CloudWatch connectors."
        fi
        summaries=$(echo "${page}" | jq -c '.ConnectorSummaries[]?')
        while IFS= read -r summary; do
            [[ -n "${summary}" ]] || continue
            check_cloudwatch_connector_summary "${summary}" "${name}"
        done <<< "${summaries}"
        next_token=$(echo "${page}" | jq -r '.NextToken // empty')
        [[ -n "${next_token}" ]] || break
    done
}

check_cloudwatch_connector_summary() {
    local summary="$1"
    local name="$2"
    local summary_arn
    local summary_name
    local detail
    local detail_tenant
    local detail_client
    local detail_role_arn

    summary_arn=$(echo "${summary}" | jq -r '.Arn')
    summary_name=$(echo "${summary}" | jq -r '.Name // empty')
    detail=$(oa get-connector --connector-identifier "${summary_arn}" --output json) ||
        die "Failed to inspect CloudWatch connector ${summary_arn}."
    detail_tenant=$(echo "${detail}" | jq -r '.Connector.ConnectorConfiguration.Azure.TenantIdentifier' |
        tr '[:upper:]' '[:lower:]')
    detail_client=$(echo "${detail}" | jq -r '.Connector.ConnectorConfiguration.Azure.ClientIdentifier' |
        tr '[:upper:]' '[:lower:]')
    detail_role_arn=$(echo "${detail}" | jq -r '.Connector.RoleArn')
    if [[ "${detail_tenant}" == "$(echo "${TENANT_ID}" | tr '[:upper:]' '[:lower:]')" ]]; then
        MATCH_BY_TENANT_ARN="${summary_arn}"
        MATCH_BY_TENANT_NAME="${summary_name}"
        MATCH_BY_TENANT_CLIENT="${detail_client}"
        MATCH_BY_TENANT_ROLE_ARN="${detail_role_arn}"
    fi
    if [[ "${summary_name}" == "${name}" ]]; then
        MATCH_BY_NAME_ARN="${summary_arn}"
    fi
}

reuse_or_reject_cloudwatch_connector() {
    local name="$1"
    local client="$2"

    if [[ -n "${MATCH_BY_TENANT_ARN}" ]]; then
        if [[ "${MATCH_BY_TENANT_NAME}" != "${name}" ]]; then
            die "A CloudWatch connector named '${MATCH_BY_TENANT_NAME}' already exists for Azure tenant ${TENANT_ID}. Only one connector per tenant is allowed, so this one can't be created. Use '${MATCH_BY_TENANT_NAME}' in the console, or delete it and rerun."
        fi
        if [[ "${MATCH_BY_TENANT_CLIENT}" != "$(echo "${client}" | tr '[:upper:]' '[:lower:]')" ]]; then
            die "A CloudWatch connector named '${name}' already exists for this tenant with a different client ID. This script never deletes a connector automatically. Delete the existing one yourself in the console (after removing its pipelines), then rerun."
        fi
        if [[ "${MATCH_BY_TENANT_ROLE_ARN}" != "${AWS_ROLE_ARN}" ]]; then
            die "A CloudWatch connector named '${name}' already exists for this tenant, but it uses IAM role ${MATCH_BY_TENANT_ROLE_ARN} instead of ${AWS_ROLE_ARN}. This script never deletes a connector automatically. Delete the existing one yourself in the console (after removing its pipelines), then rerun."
        fi
        CLOUDWATCH_CONNECTOR_ARN="${MATCH_BY_TENANT_ARN}"
        CLOUDWATCH_CONNECTOR_STATUS_FINAL="existing"
        log "CloudWatch connector '${name}' already exists for this tenant. Reusing it."
        return 0
    fi

    if [[ -n "${MATCH_BY_NAME_ARN}" ]]; then
        die "A CloudWatch connector named '${name}' already exists for a different Azure tenant. Pick another connection name in the console and copy the new command."
    fi

    die "The CloudWatch connector '${name}' could not be created or matched to an existing connector. Rerun the same command."
}

list_config_connectors_paginated() {
    local next_token=""
    local page
    local summaries="[]"

    while :; do
        if [[ -n "${next_token}" ]]; then
            page=$(aws configservice "$@" --starting-token "${next_token}" --output json) || return 1
        else
            page=$(aws configservice "$@" --output json) || return 1
        fi
        summaries=$(jq -c --argjson acc "${summaries}" '$acc + (.ConnectorSummaries // [])' <<< "${page}")
        next_token=$(echo "${page}" | jq -r '.NextToken // empty')
        [[ -n "${next_token}" ]] || break
    done
    jq -cn --argjson summaries "${summaries}" '{ConnectorSummaries: $summaries}'
}

CONFIG_CONNECTORS_LIST_JSON=""
CONFIG_CONNECTORS_LIST_FETCHED=false

list_config_connectors() {
    if [[ "${CONFIG_CONNECTORS_LIST_FETCHED}" == false ]]; then
        if CONFIG_CONNECTORS_LIST_JSON=$(list_config_connectors_paginated \
            list-connectors --filters filterName=provider,filterValues=AZURE \
            --region "${AWS_REGION}" 2>/dev/null); then
            CONFIG_CONNECTORS_LIST_FETCHED=true
        else
            CONFIG_CONNECTORS_LIST_JSON=""
        fi
    fi
    printf '%s' "${CONFIG_CONNECTORS_LIST_JSON}"
}

find_config_connector_owner() {
    local existing
    local arn
    local detail
    local client

    existing=$(list_config_connectors)
    [[ -n "${existing}" ]] || return 0
    arn=$(echo "${existing}" | jq -r --arg tenant "${TENANT_ID}" \
        '.ConnectorSummaries[] | select((.tenantIdentifier | ascii_downcase) == ($tenant | ascii_downcase)) | .arn' | head -n1)
    [[ -n "${arn}" ]] || return 0

    detail=$(aws configservice get-connector --arn "${arn}" --region "${AWS_REGION}" --output json 2>/dev/null) || return 0
    client=$(echo "${detail}" | jq -r '.Connector.connectorConfiguration.azure.clientIdentifier // empty')
    [[ -n "${client}" ]] || return 0

    echo "${arn} ${client}"
}

backfill_config_connector_tags() {
    local arn="$1"
    local what="$2"
    local existing_tags
    local missing_tags=()

    if [[ "${DRY_RUN}" == true ]]; then
        return 0
    fi

    existing_tags=$(aws configservice list-tags-for-resource --resource-arn "${arn}" --region "${AWS_REGION}" --output json |
        jq -c '[.Tags[]?.Key]')
    echo "${existing_tags}" | jq -e 'index("aws-config-account")' >/dev/null ||
        missing_tags+=("Key=aws-config-account,Value=${AWS_ACCOUNT_ID}")
    echo "${existing_tags}" | jq -e 'index("aws-config-region")' >/dev/null ||
        missing_tags+=("Key=aws-config-region,Value=${AWS_REGION}")
    if [[ ${#missing_tags[@]} -gt 0 ]]; then
        aws configservice tag-resource --resource-arn "${arn}" --tags "${missing_tags[@]}" --region "${AWS_REGION}" >/dev/null ||
            die "Failed to tag ${what} ${arn}."
    fi
}

ensure_config_connector() {
    local client="$1"
    local config

    config=$(config_connector_configuration "${client}")

    if [[ "${DRY_RUN}" == true ]]; then
        log "Would create or reuse the AWS Config connector."
        CONFIG_CONNECTOR_ARN="<dry-run-connector-arn>"
        CONFIG_CONNECTOR_STATUS_FINAL="create"
        return 0
    fi

    try_create_config_connector "${config}"
    if [[ "${CONFIG_CONNECTOR_CREATED}" == true ]]; then
        return 0
    fi

    find_config_connector_match
    finalize_config_connector_match "${client}"
}

try_create_config_connector() {
    local config="$1"
    local result

    CONFIG_CONNECTOR_CREATED=false
    result=$(try_create_connector "AWS Config connector" \
        aws configservice put-connector --connector-configuration "${config}" \
        --tags "Key=aws-config-account,Value=${AWS_ACCOUNT_ID}" "Key=aws-config-region,Value=${AWS_REGION}" \
        --region "${AWS_REGION}" --output json)
    if [[ -n "${result}" ]]; then
        CONFIG_CONNECTOR_ARN=$(echo "${result}" | jq -r '.Arn')
        CONFIG_CONNECTOR_STATUS_FINAL="create"
        CONFIG_CONNECTOR_CREATED=true
        log "AWS Config connector (created)."
    fi
}

find_config_connector_match() {
    local existing
    local detail

    existing=$(list_config_connectors_paginated list-connectors --filters filterName=provider,filterValues=AZURE \
        --region "${AWS_REGION}") ||
        die "Failed to list AWS Config connectors."
    CONFIG_MATCH_ARN=$(echo "${existing}" | jq -r --arg tenant "${TENANT_ID}" \
        '.ConnectorSummaries[] | select((.tenantIdentifier | ascii_downcase) == ($tenant | ascii_downcase)) | .arn' | head -n1)
    [[ -n "${CONFIG_MATCH_ARN}" ]] ||
        die "The AWS Config connector could not be created or matched to an existing connector for this tenant. Rerun the same command."

    detail=$(aws configservice get-connector --arn "${CONFIG_MATCH_ARN}" --region "${AWS_REGION}" --output json) ||
        die "Failed to inspect AWS Config connector ${CONFIG_MATCH_ARN}."
    CONFIG_MATCH_CLIENT=$(echo "${detail}" | jq -r '.Connector.connectorConfiguration.azure.clientIdentifier' |
        tr '[:upper:]' '[:lower:]')
}

finalize_config_connector_match() {
    local client="$1"

    CONFIG_CONNECTOR_ARN="${CONFIG_MATCH_ARN}"
    backfill_config_connector_tags "${CONFIG_MATCH_ARN}" "AWS Config connector"
    if [[ "${CONFIG_MATCH_CLIENT}" == "$(echo "${client}" | tr '[:upper:]' '[:lower:]')" ]]; then
        CONFIG_CONNECTOR_STATUS_FINAL="existing"
        log "AWS Config connector (existing)."
        return 0
    fi

    CONFIG_CONNECTOR_STATUS_FINAL="reused"
    warn "AWS Config connector reused from another application (client ID ${CONFIG_MATCH_CLIENT}). Topology and resource tags only cover what that application can read."
}

check_connector_role_exists() {
    local role_json
    local trust_doc
    local existing_connector
    local existing_pipeline
    local has_policy=false
    local policy_unknown=false
    local simulate_json

    compute_expected_role_trust

    role_json=$(read_optional_aws_json "connector role ${AWS_ROLE_NAME}" \
        aws iam get-role --role-name "${AWS_ROLE_NAME}" --output json) || exit 1
    [[ -n "${role_json}" ]] ||
        die "Connector role ${AWS_ROLE_NAME} does not exist. Run the script with --steps aws-identity first, or add the permissions yourself."

    trust_doc=$(echo "${role_json}" | jq -c '.Role.AssumeRolePolicyDocument')
    existing_connector=$(echo "${trust_doc}" | jq -c --arg sid "${CONNECTOR_TRUST_SID}" '.Statement[] | select(.Sid == $sid)')
    existing_pipeline=$(echo "${trust_doc}" | jq -c --arg sid "${PIPELINE_TRUST_SID}" '.Statement[] | select(.Sid == $sid)')
    [[ -n "${existing_connector}" && "$(echo "${existing_connector}" | jq -Sc .)" == "$(echo "${CONNECTOR_TRUST_STATEMENT}" | jq -Sc .)" ]] ||
        existing_connector=""
    [[ -n "${existing_pipeline}" && "$(echo "${existing_pipeline}" | jq -Sc .)" == "$(echo "${PIPELINE_TRUST_STATEMENT}" | jq -Sc .)" ]] ||
        existing_pipeline=""

    if simulate_json=$(aws iam simulate-principal-policy \
        --policy-source-arn "${AWS_ROLE_ARN}" \
        --action-names sts:GetWebIdentityToken \
        --context-entries "ContextKeyName=sts:IdentityTokenAudience,ContextKeyType=string,ContextKeyValues=${AUDIENCE}" \
        --output json 2>/dev/null); then
        if echo "${simulate_json}" | jq -e \
            '[.EvaluationResults[]? | select(.EvalDecision == "allowed")] | length > 0' >/dev/null; then
            has_policy=true
        fi
    else
        policy_unknown=true
    fi

    if [[ -z "${existing_connector}" || -z "${existing_pipeline}" || "${has_policy}" != true ]]; then
        if [[ -n "${existing_connector}" && -n "${existing_pipeline}" && "${policy_unknown}" == true ]]; then
            warn "Could not verify connector role ${AWS_ROLE_NAME}'s sts:GetWebIdentityToken permission; continuing. If the connectors step fails on token exchange, run the script with --steps aws-identity to fix it."
        else
            die "Connector role ${AWS_ROLE_NAME} is missing the trust or permissions this script needs. Run the script with --steps aws-identity first, or add the permissions yourself."
        fi
    fi
}

plan_connectors() {
    if ! has_step aws-identity; then
        check_connector_role_exists
    fi

    CLOUDWATCH_CONNECTOR_STATUS="create"
    CONFIG_CONNECTOR_STATUS="create"

    plan_cloudwatch_connector_status
    plan_config_connector_status
}

plan_cloudwatch_connector_status() {
    local page
    local next_token=""
    local summary
    local summary_arn
    local detail_tenant

    while :; do
        if [[ -n "${next_token}" ]]; then
            page=$(oa list-connectors --next-token "${next_token}" --output json 2>/dev/null) || page=""
        else
            page=$(oa list-connectors --output json 2>/dev/null) || page=""
        fi
        [[ -n "${page}" ]] || break
        summary=$(echo "${page}" | jq -c --arg name "${CONNECTION_NAME}" \
            '.ConnectorSummaries[]? | select(.Name == $name)' | head -n1)
        if [[ -n "${summary}" ]]; then
            summary_arn=$(echo "${summary}" | jq -r '.Arn')
            detail_tenant=$(oa get-connector --connector-identifier "${summary_arn}" --output json 2>/dev/null |
                jq -r '.Connector.ConnectorConfiguration.Azure.TenantIdentifier // empty' | tr '[:upper:]' '[:lower:]')
            if [[ "${detail_tenant}" == "$(echo "${TENANT_ID}" | tr '[:upper:]' '[:lower:]')" ]]; then
                CLOUDWATCH_CONNECTOR_STATUS="existing"
            fi
            break
        fi
        next_token=$(echo "${page}" | jq -r '.NextToken // empty')
        [[ -n "${next_token}" ]] || break
    done
}

plan_config_connector_status() {
    local config_existing

    if [[ "${TELEMETRY_ONLY}" == false ]]; then
        config_existing=$(list_config_connectors)
        if [[ -n "${config_existing}" ]] && echo "${config_existing}" | jq -e \
            --arg tenant "${TENANT_ID}" \
            '.ConnectorSummaries[]? | select((.tenantIdentifier | ascii_downcase) == ($tenant | ascii_downcase))' \
            >/dev/null 2>&1; then
            CONFIG_CONNECTOR_STATUS="existing"
        fi
    fi
}

apply_connectors() {
    step_progress "Connectors"
    ensure_cloudwatch_connector "${CONNECTION_NAME}" "${APP_ID}"

    CONFIG_CONNECTOR_ARN=""
    if [[ "${TELEMETRY_ONLY}" == false ]]; then
        if [[ -n "${CONFIG_CONNECTOR_OWNER_ARN:-}" ]]; then
            CONFIG_CONNECTOR_ARN="${CONFIG_CONNECTOR_OWNER_ARN}"
            CONFIG_CONNECTOR_STATUS_FINAL="reused"
            backfill_config_connector_tags "${CONFIG_CONNECTOR_ARN}" "AWS Config connector"
            warn "AWS Config connector reused from another application (client ID ${CONFIG_CONNECTOR_OWNER_CLIENT_ID}). Topology and resource tags only cover what that application can read."
        else
            ensure_config_connector "${CONFIG_APP_ID}"
        fi
    fi
}

verify_connection() {
    [[ "${DRY_RUN}" == true ]] && return 0 || true

    step_progress "Verifying Azure access"
    log "Waiting for Azure permissions to take effect (can take up to 10 min) ..."
    sleep 60
    local attempt=0
    while (( attempt < 20 )); do
        if oa list-resources-by-connector \
            --connector-identifier "${CLOUDWATCH_CONNECTOR_ARN}" \
            --selector '{"Azure":{"Subscriptions":{}}}' \
            --output json >/dev/null 2>&1; then
            log "Verified Azure access."
            return 0
        fi
        sleep 30
        attempt=$((attempt + 1))
    done
    if has_step azure-identity; then
        die "Everything was created, but Azure hasn't finished applying the permissions yet. Wait a few minutes and rerun the same command. Finished steps are skipped."
    else
        die "Everything was created, but Azure hasn't finished applying the permissions yet. Wait a few minutes and rerun the same command, or double-check that --azure-tenant-id, --telemetry-app-id, and --config-app-id match an existing azure-identity run. Finished steps are skipped."
    fi
}

print_plan() {
    local issuer_display="${AWS_ISSUER_URL}"
    [[ -n "${issuer_display}" ]] || issuer_display="<to be enabled - AWS outbound identity federation not yet created>"

    if has_step aws-identity; then
        print_aws_identity_plan
    fi
    if has_step azure-identity; then
        print_azure_identity_plan "${issuer_display}"
    fi
    if has_step connectors; then
        print_connectors_plan
    fi

    if [[ "${DRY_RUN}" == true ]]; then
        log "DRY RUN - the plan above is printed only; no Azure object will be created or changed."
    fi
}

print_aws_identity_plan() {
    local federation_plan="will be enabled"
    [[ "${FEDERATION_STATUS}" == existing ]] && federation_plan="already enabled" || true

    local role_plan
    case "${ROLE_STATUS}" in
        create) role_plan="will be created" ;;
        update) role_plan="exists, will be updated to add what is missing" ;;
        existing) role_plan="exists, already has what it needs" ;;
    esac

    cat >&2 <<EOF

This sets up the AWS side of the connection:

  Outbound identity federation: ${federation_plan}
  Connector role ${AWS_ROLE_NAME}: ${role_plan}
    trusts ${CONNECTOR_SERVICE_PRINCIPAL} and ${PIPELINE_SERVICE_PRINCIPAL}
EOF
}

print_azure_identity_plan() {
    local issuer_display="$1"

    print_tenant_info
    print_telemetry_identity_plan "${issuer_display}"
    print_config_identity_plan "${issuer_display}"
    print_azure_identity_footer
}

print_tenant_info() {
    if [[ -n "${TENANT_NAME}" ]]; then
        log "Azure tenant:   ${TENANT_NAME} (${TENANT_ID})"
    else
        log "Azure tenant:   ${TENANT_ID}"
    fi
    if [[ -n "${TENANT_DOMAIN}" ]]; then
        log "Tenant domain:  ${TENANT_DOMAIN}"
    fi
    log "Signed in as:   $(echo "${ACCOUNT_JSON}" | jq -r '.user.name // "unknown"')"
}

print_telemetry_identity_plan() {
    local issuer_display="$1"

    cat >&2 <<EOF

In tenant ${TENANT_ID} this creates - or adopts, where the ownership tags already
match - each Entra application below, with its service principal, exactly one
federated credential, and the role grants shown below:

  1. Telemetry identity - AWS CloudWatch
       application:     ${APP_NAME}
       ownership tags:  ${TELEMETRY_ACCOUNT_TAG}, ${TELEMETRY_REGION_TAG}
       credential:      ${TELEMETRY_FED_CRED_NAME}
         trusts issuer  ${issuer_display}
         for subject    ${AWS_ROLE_ARN}
       role grants:     Reader and Monitoring Reader at ${MANAGEMENT_GROUP_SCOPE}
EOF
}

print_config_identity_plan() {
    local issuer_display="$1"

    if [[ "${TELEMETRY_ONLY}" == false && -n "${CONFIG_CONNECTOR_OWNER_ARN}" ]]; then
        cat >&2 <<EOF
  2. Config identity - skipped: an AWS Config connector for this tenant already
       exists under another application (client ID ${CONFIG_CONNECTOR_OWNER_CLIENT_ID}).
EOF
    elif [[ "${TELEMETRY_ONLY}" == false ]]; then
        cat >&2 <<EOF
  2. Config identity - AWS Config
       application:     ${CONFIG_APP_NAME}
       ownership tags:  ${CONFIG_ACCOUNT_TAG}, ${CONFIG_REGION_TAG}
       identifier URI:  ${CONFIG_IDENTIFIER_URI}
       credential:      ${CONFIG_FED_CRED_NAME}
         trusts issuer  ${issuer_display}
         for subject    ${CONFIG_SLR_ARN}
       role grant:      Reader at ${MANAGEMENT_GROUP_SCOPE}
EOF
    fi
}

print_azure_identity_footer() {
    if has_step aws-identity; then
        cat >&2 <<EOF
Reader and Monitoring Reader are read-only and tenant-wide. Nothing
else is created in Azure: no Event Hub and no diagnostic setting. AWS trust in
account ${AWS_ACCOUNT_ID} is already set up, and aborting here doesn't undo it.
EOF
    else
        cat >&2 <<EOF
Reader and Monitoring Reader are read-only and tenant-wide. Nothing
else is created: no Event Hub, no diagnostic setting, and nothing on the AWS side.
EOF
    fi
}

print_connectors_plan() {
    cat >&2 <<EOF

This sets up the connectors for Azure tenant ${TENANT_ID}:

  CloudWatch connector '${CONNECTION_NAME}': $([[ "${CLOUDWATCH_CONNECTOR_STATUS}" == existing ]] && echo "already exists, will be reused" || echo "will be created")
EOF
    if [[ "${TELEMETRY_ONLY}" == false ]]; then
        cat >&2 <<EOF
  AWS Config connector: $([[ "${CONFIG_CONNECTOR_STATUS}" == existing ]] && echo "already exists, will be reused" || echo "will be created")
EOF
    fi
}

confirm() {
    local reply
    local discarded

    if [[ "${DRY_RUN}" == true ]]; then
        return 0
    fi

    if [[ ! -t 0 ]]; then
        die "Stdin is not a terminal, so there's no way to confirm interactively. Run this script directly in a terminal, or use --dry-run to preview the plan without applying it."
    fi

    while IFS= read -r -t 1 discarded; do :; done

    if has_step azure-identity; then
        printf 'Continue against tenant %s? [Enter to continue, Ctrl-C to abort] ' "${TENANT_ID}" >&2
    else
        printf 'Continue? [Enter to continue, Ctrl-C to abort] ' >&2
    fi
    read -r reply || die "Aborted."
    if [[ -n "${reply}" && ! "${reply}" =~ ^[Yy]([Ee][Ss])?$ ]]; then
        die "Aborted at confirmation."
    fi
}

apply_azure_identity() {
    provision_telemetry_identity
    provision_config_identity
}

provision_telemetry_identity() {
    step_progress "Microsoft Entra applications"
    log "Provisioning the telemetry identity..."
    TELEMETRY_APP_IDS=$(ensure_application_by_tag "${APP_NAME}" "${TELEMETRY_TAGS}" "")
    read -r APP_ID APP_OBJECT_ID TELEMETRY_APP_STATUS <<< "${TELEMETRY_APP_IDS}"
    SP_OBJECT_ID=$(ensure_service_principal "${APP_ID}")
    merge_graph_tags applications "${APP_OBJECT_ID}" "${TELEMETRY_TAGS}"
    if [[ "${SP_OBJECT_ID}" != "<dry-run-service-principal-id>" ]]; then
        merge_graph_tags servicePrincipals "${SP_OBJECT_ID}" "${TELEMETRY_TAGS}"
        validate_effective_roles_at_scope \
            "${SP_OBJECT_ID}" \
            "${MANAGEMENT_GROUP_SCOPE}" \
            "telemetry service principal at the tenant root management group" \
            "${READER_ROLE_ID}" \
            "${MONITORING_READER_ROLE_ID}"
    fi
    ensure_fic_by_name \
        "${APP_ID}" "${TELEMETRY_FED_CRED_NAME}" "${AWS_ISSUER_URL}" "${AWS_ROLE_ARN}" \
        "${AUDIENCE}" "${TELEMETRY_FED_CRED_DESCRIPTION}"
    TELEMETRY_FIC_SET=$(jq -cn \
        --argjson primary "$(fic_spec "${TELEMETRY_FED_CRED_NAME}" "${AWS_ISSUER_URL}" "${AWS_ROLE_ARN}" "${AUDIENCE}")" \
        '[$primary]')
    revalidate_identity \
        "${APP_ID}" "${APP_OBJECT_ID}" "${SP_OBJECT_ID}" \
        "${TELEMETRY_TAGS}" "${TELEMETRY_FIC_SET}"
    assign_root_reader "${SP_OBJECT_ID}" "telemetry"
    assign_root_monitoring_reader "${SP_OBJECT_ID}" "telemetry"
}

provision_config_identity() {
    CONFIG_APP_ID=""
    CONFIG_SP_OBJECT_ID=""
    CONFIG_APP_STATUS=""
    if [[ "${TELEMETRY_ONLY}" == false ]]; then
        if [[ -n "${CONFIG_CONNECTOR_OWNER_ARN}" ]]; then
            report_foreign_owned_config_connector
            return 0
        fi
        create_config_identity
    fi
}

report_foreign_owned_config_connector() {
    CONFIG_APP_ID="${CONFIG_CONNECTOR_OWNER_CLIENT_ID}"
    CONFIG_APP_STATUS="reused"
    local orphaned_app_id
    orphaned_app_id=$(find_existing_app_by_tag "${CONFIG_TAGS}")
    if [[ -n "${orphaned_app_id}" ]]; then
        warn "An AWS Config connector for this tenant already exists under another application (client ID ${CONFIG_CONNECTOR_OWNER_CLIENT_ID}). This run's own Config application (client ID ${orphaned_app_id}), left over from an earlier run, is not being used; delete it once you've confirmed it isn't needed."
    else
        log "An AWS Config connector for this tenant already exists under another application (client ID ${CONFIG_CONNECTOR_OWNER_CLIENT_ID}); not creating a Config identity."
    fi
}

create_config_identity() {
    log "Provisioning the AWS Config identity..."
    CONFIG_APP_IDS=$(ensure_application_by_tag "${CONFIG_APP_NAME}" "${CONFIG_TAGS}" "${CONFIG_IDENTIFIER_URI}")
    read -r CONFIG_APP_ID CONFIG_APP_OBJECT_ID CONFIG_APP_STATUS <<< "${CONFIG_APP_IDS}"
    CONFIG_SP_OBJECT_ID=$(ensure_service_principal "${CONFIG_APP_ID}")
    merge_graph_tags applications "${CONFIG_APP_OBJECT_ID}" "${CONFIG_TAGS}"
    if [[ "${CONFIG_SP_OBJECT_ID}" != "<dry-run-service-principal-id>" ]]; then
        merge_graph_tags servicePrincipals "${CONFIG_SP_OBJECT_ID}" "${CONFIG_TAGS}"
        validate_effective_roles_at_scope \
            "${CONFIG_SP_OBJECT_ID}" \
            "${MANAGEMENT_GROUP_SCOPE}" \
            "Config service principal at the tenant root management group" \
            "${READER_ROLE_ID}"
    fi
    ensure_fic_by_name \
        "${CONFIG_APP_ID}" "${CONFIG_FED_CRED_NAME}" "${AWS_ISSUER_URL}" "${CONFIG_SLR_ARN}" \
        "${AUDIENCE}" "${CONFIG_FED_CRED_DESCRIPTION}"
    CONFIG_FIC_SET=$(jq -cn \
        --argjson prod "$(fic_spec "${CONFIG_FED_CRED_NAME}" "${AWS_ISSUER_URL}" "${CONFIG_SLR_ARN}" "${AUDIENCE}")" \
        '[$prod]')
    revalidate_identity \
        "${CONFIG_APP_ID}" "${CONFIG_APP_OBJECT_ID}" "${CONFIG_SP_OBJECT_ID}" \
        "${CONFIG_TAGS}" "${CONFIG_FIC_SET}"
    assign_root_reader "${CONFIG_SP_OBJECT_ID}" "Config"
}

build_aws_json() {
    jq -cn \
        --arg accountId "${AWS_ACCOUNT_ID:-}" \
        --arg region "${AWS_REGION:-}" \
        --arg issuer "${AWS_ISSUER_URL:-}" \
        --arg fedStatus "$(to_status "${FEDERATION_STATUS:-unknown}")" \
        --arg roleArn "${AWS_ROLE_ARN:-}" \
        --arg roleStatus "$(to_status "${ROLE_STATUS:-unknown}")" \
        '{accountId: $accountId, region: $region,
          outboundIdentityFederation: {issuer: $issuer, status: $fedStatus},
          connectorRole: {arn: $roleArn, status: $roleStatus}}'
}

build_azure_json() {
    local telemetry_json
    local config_json="null"

    telemetry_json=$(jq -cn \
        --arg displayName "${APP_NAME:-}" --arg appId "${APP_ID:-}" \
        --arg status "$(to_status "${TELEMETRY_APP_STATUS:-unknown}")" \
        '{displayName: $displayName, appId: $appId, roles: ["Reader", "Monitoring Reader"], status: $status}')

    if [[ "${TELEMETRY_ONLY}" == false ]]; then
        if [[ -n "${CONFIG_CONNECTOR_OWNER_ARN:-}" ]]; then
            config_json=$(jq -cn --arg appId "${CONFIG_CONNECTOR_OWNER_CLIENT_ID:-}" \
                '{appId: $appId, roles: [], status: "reused"}')
        elif [[ -n "${CONFIG_APP_ID:-}" ]]; then
            config_json=$(jq -cn \
                --arg displayName "${CONFIG_APP_NAME:-}" --arg appId "${CONFIG_APP_ID:-}" \
                --arg status "$(to_status "${CONFIG_APP_STATUS:-unknown}")" \
                '{displayName: $displayName, appId: $appId, roles: ["Reader"], status: $status}')
        fi
    fi

    jq -cn \
        --arg tenantId "${TENANT_ID:-}" \
        --argjson telemetry "${telemetry_json}" \
        --argjson config "${config_json}" \
        '{tenantId: $tenantId, telemetryApplication: $telemetry}
         + (if $config == null then {} else {configApplication: $config} end)'
}

build_connectors_json() {
    local cw_json
    local config_json="null"

    cw_json=$(jq -cn \
        --arg name "${CONNECTION_NAME:-}" --arg arn "${CLOUDWATCH_CONNECTOR_ARN:-}" \
        --arg status "$(to_status "${CLOUDWATCH_CONNECTOR_STATUS_FINAL:-unknown}")" \
        '{name: $name, arn: $arn, status: $status}')

    if [[ "${TELEMETRY_ONLY}" == false && -n "${CONFIG_CONNECTOR_ARN:-}" ]]; then
        config_json=$(jq -cn \
            --arg arn "${CONFIG_CONNECTOR_ARN}" \
            --arg status "$(to_status "${CONFIG_CONNECTOR_STATUS_FINAL:-unknown}")" \
            '{arn: $arn, status: $status}')
    fi

    jq -cn \
        --argjson cw "${cw_json}" --argjson config "${config_json}" \
        '{cloudWatch: $cw} + (if $config == null then {} else {awsConfig: $config} end)'
}

build_warnings_json() {
    printf '%s\n' "${WARNINGS[@]:-}" | jq -Rsc '[splits("\n")] | map(select(length > 0))'
}

collect_preflight_issues() {
    PREFLIGHT_ISSUES_FLAT=()
    local item
    for item in "${COMMAND_ISSUES[@]:-}" "${AWS_ISSUES[@]:-}" "${AZURE_ISSUES[@]:-}"; do
        if [[ -n "${item}" ]]; then
            PREFLIGHT_ISSUES_FLAT+=("${item}")
        fi
    done
}

preflight_errors_json() {
    collect_preflight_issues
    if [[ ${#PREFLIGHT_ISSUES_FLAT[@]} -eq 0 ]]; then
        printf '[]'
    else
        jq -cn '$ARGS.positional' --args "${PREFLIGHT_ISSUES_FLAT[@]}"
    fi
}

json_escape() {
    local s="$1"
    s="${s//\\/\\\\}"
    s="${s//\"/\\\"}"
    s="${s//$'\n'/\\n}"
    s="${s//$'\r'/\\r}"
    s="${s//$'\t'/\\t}"
    s="${s//[$'\x01'-$'\x1f']/}"
    printf '%s' "${s}"
}

json_string_array() {
    local out="[" first=true item
    for item in "$@"; do
        [[ "${first}" == true ]] || out+=","
        first=false
        out+="\"$(json_escape "${item}")\""
    done
    printf '%s' "${out}]"
}

print_failure_json_no_jq() {
    local steps_arr=()
    IFS=',' read -ra steps_arr <<< "${STEPS:-}"
    collect_preflight_issues

    local steps_json preflight_json
    if [[ ${#steps_arr[@]} -eq 0 ]]; then
        steps_json="[]"
    else
        steps_json=$(json_string_array "${steps_arr[@]}")
    fi
    if [[ ${#PREFLIGHT_ISSUES_FLAT[@]} -eq 0 ]]; then
        preflight_json="[]"
    else
        preflight_json=$(json_string_array "${PREFLIGHT_ISSUES_FLAT[@]}")
    fi

    local extra=""
    [[ -z "${CURRENT_STEP_LABEL:-}" ]] || extra+=",\"failedStep\":\"$(json_escape "${CURRENT_STEP_LABEL}")\""
    extra+=",\"error\":\"$(json_escape "${LAST_ERROR_MSG:-}")\""
    [[ -z "${LAST_ERROR_FIX:-}" ]] || extra+=",\"fix\":\"$(json_escape "${LAST_ERROR_FIX}")\""

    printf '{"status":"failed","steps":%s%s,"completedSteps":[],"preFlightErrors":%s,"warnings":[]}\n' \
        "${steps_json}" "${extra}" "${preflight_json}" >&3
}

print_failure_json() {
    if [[ "${HAVE_JQ}" != true ]]; then
        print_failure_json_no_jq
        return
    fi

    local steps_json
    local aws_json="null"
    local azure_json="null"
    local connectors_json="null"
    local warnings_json="[]"

    steps_json=$(jq -cn --arg s "${STEPS:-}" '$s | split(",") | map(select(length > 0))' 2>/dev/null) || steps_json="[]"
    if has_step aws-identity 2>/dev/null; then
        aws_json=$(build_aws_json 2>/dev/null) || aws_json="null"
    fi
    if has_step azure-identity 2>/dev/null; then
        azure_json=$(build_azure_json 2>/dev/null) || azure_json="null"
    fi
    if has_step connectors 2>/dev/null; then
        connectors_json=$(build_connectors_json 2>/dev/null) || connectors_json="null"
    fi
    warnings_json=$(build_warnings_json 2>/dev/null) || warnings_json="[]"

    local jq_flags=(-nM)
    [[ -t 3 ]] || jq_flags+=(-c)
    jq "${jq_flags[@]}" \
        --arg status "failed" \
        --argjson steps "${steps_json}" \
        --arg failedStep "${CURRENT_STEP_LABEL:-}" \
        --arg error "${LAST_ERROR_MSG:-}" \
        --arg fix "${LAST_ERROR_FIX:-}" \
        --argjson completedSteps "$(printf '%s\n' "${COMPLETED_STEPS[@]:-}" | jq -Rsc '[splits("\n")] | map(select(length > 0))' 2>/dev/null || echo '[]')" \
        --argjson aws "${aws_json}" --argjson azure "${azure_json}" --argjson connectors "${connectors_json}" \
        --argjson warnings "${warnings_json}" \
        --argjson preFlightErrors "$(preflight_errors_json 2>/dev/null || echo '[]')" \
        '{status: $status, steps: $steps}
         + (if $failedStep != "" then {failedStep: $failedStep} else {} end)
         + {error: $error}
         + (if $fix != "" then {fix: $fix} else {} end)
         + {completedSteps: $completedSteps}
         + (if $aws == null then {} else {aws: $aws} end)
         + (if $azure == null then {} else {azure: $azure} end)
         + (if $connectors == null then {} else {connectors: $connectors} end)
         + {preFlightErrors: $preFlightErrors}
         + {warnings: $warnings}' >&3 2>/dev/null || true
}

print_summary() {
    if [[ "${DRY_RUN}" == true ]]; then
        log "Dry run complete. Nothing was created; re-run without --dry-run to apply the plan."
        return 0
    fi

    local steps_json
    steps_json=$(jq -cn --arg s "${STEPS}" '$s | split(",")')

    local aws_json="null"
    local azure_json="null"
    local connectors_json="null"
    has_step aws-identity && aws_json=$(build_aws_json)
    has_step azure-identity && azure_json=$(build_azure_json)
    has_step connectors && connectors_json=$(build_connectors_json)

    local summary_json
    local jq_flags=(-nM)
    [[ -t 1 ]] || jq_flags+=(-c)
    summary_json=$(jq "${jq_flags[@]}" \
        --arg status "succeeded" \
        --argjson steps "${steps_json}" \
        --argjson aws "${aws_json}" \
        --argjson azure "${azure_json}" \
        --argjson connectors "${connectors_json}" \
        --argjson warnings "$(build_warnings_json)" \
        '{status: $status, steps: $steps}
         + (if $aws == null then {} else {aws: $aws} end)
         + (if $azure == null then {} else {azure: $azure} end)
         + (if $connectors == null then {} else {connectors: $connectors} end)
         + {warnings: $warnings}')

    print_paste_back_block "${summary_json}"
}

print_paste_back_block() {
    local summary_json="$1"

    if has_step connectors; then
        [[ -n "${LOG_FILE}" ]] && log "Log: ${LOG_FILE}" || true
        echo "..................................................." >&2
        echo "Setup complete for ${STEPS}. Return to console and continue." >&2
        printf '%s\n' "${summary_json}"
    elif has_step azure-identity; then
        log "Identity setup complete."
        [[ -n "${LOG_FILE}" ]] && log "Log: ${LOG_FILE}" || true
        printf '%s\n' "${summary_json}"
        echo "..................................................." >&2
        if [[ "${TELEMETRY_ONLY}" == true ]]; then
            cat >&2 <<EOF

Paste this into the console for AWS account ${AWS_ACCOUNT_ID} in ${AWS_REGION}:

  {"tenantId":"${TENANT_ID}","appId":"${APP_ID}"}
EOF
        else
            cat >&2 <<EOF

Paste this into the console for AWS account ${AWS_ACCOUNT_ID} in ${AWS_REGION}:

  {"tenantId":"${TENANT_ID}","appId":"${APP_ID}","configAppId":"${CONFIG_APP_ID}"}
EOF
        fi
    elif has_step aws-identity; then
        printf '%s\n' "${summary_json}"
        log "Identity setup complete."
        [[ -n "${LOG_FILE}" ]] && log "Log: ${LOG_FILE}" || true
    fi
}

main() {
    trap 'on_error "${LINENO}"' ERR

    parse_args "$@"
    validate_inputs
    build_step_labels
    check_tools

    if [[ "${DRY_RUN}" == false ]]; then
        LOG_FILE="./cloudwatch-azure-setup-$(date -u +%Y%m%dT%H%M).log"
        (umask 077 && touch "${LOG_FILE}") 2>/dev/null || LOG_FILE=""
    fi

    read_context
    check_permissions
    report_preflight_issues

    if has_step aws-identity; then
        plan_aws_identity
    fi
    if has_step azure-identity; then
        plan_azure_identity
    fi
    if has_step connectors; then
        plan_connectors
    fi
    print_plan
    confirm
    if has_step aws-identity; then
        apply_aws_identity
        mark_step_completed "AWS identity ($(to_status "${ROLE_STATUS}"))"
    fi
    if has_step azure-identity; then
        apply_azure_identity
        local azure_app_count=1
        [[ "${TELEMETRY_ONLY}" == false && -z "${CONFIG_CONNECTOR_OWNER_ARN:-}" ]] && azure_app_count=2 || true
        mark_step_completed "Azure identity (${azure_app_count} app(s) $(to_status "${TELEMETRY_APP_STATUS}"))"
    fi
    if has_step connectors; then
        apply_connectors
        mark_step_completed "Connectors"
    fi
    if has_step connectors; then
        verify_connection
        mark_step_completed "Verified"
    fi
    print_summary
}

main "$@"
