#!/usr/bin/env bash
# Script 3 of 3: create the Azure resources used by the AWS Config connector.
#
# AWS Config inventories every enabled subscription in the tenant through the
# Config service principal created by Script 1. This script creates or adopts
# the shared activitylog Event Hub resources and configures tenant and
# subscription Activity Logs to stream to that hub.
#
# Progress is written to stderr. On success, stdout contains one JSON object
# (pretty-printed when stdout is a terminal, compact otherwise) with the
# created or adopted resource identifiers and the exact policy assignment and
# subscription snapshot used to start remediation. A subscription that fails
# to start remediation doesn't fail the script; each target's
# failedSubscriptions reports it instead. A subscription with an already
# in-progress remediation for the same policy assignment is adopted instead
# of started again, and reported in that target's alreadyRunning.

set -euo pipefail

export AZURE_EXTENSION_USE_DYNAMIC_INSTALL=no
export LC_ALL=C

trap 'exit 130' INT TERM HUP

MIN_AZ_VERSION="2.47.0"
# The policy definition and custom roles are shared by every AWS consumer in
# this tenant. Never bump this version or change their permissions without an
# explicit in-place migration that supports consumers running an older script.
# A mismatch intentionally fails closed rather than overwriting shared RBAC.
POLICY_VERSION="1.0.0"
PREFIX="aws-cloudwatch-config"
EVENT_HUB_NAME="activitylog"
CONSUMER_GROUP_NAME="awsconfig"
EXPORT_RULE_NAME="${PREFIX}-export"
EVENT_HUB_SKU="Standard"
EVENT_HUB_CAPACITY=1
EVENT_HUB_PARTITION_COUNT=4
EVENT_HUB_RETENTION_HOURS=168
DATA_RECEIVER_ROLE_ID="a638d3c7-ab3a-418d-83e6-5f17a39d4fde"
READER_ROLE_ID="acdd72a7-3385-48ef-bd42-f606fba81ae7"
DEPLOYER_ROLE_ID="f94f3afd-bf23-4c2d-a6cd-2f3511fa39d0"
LIST_KEYS_ROLE_ID="721f5565-afb9-4375-9bd1-3a3ac0e7798f"
DEPLOYER_ROLE_NAME="${PREFIX}-activitylog-deployer"
LIST_KEYS_ROLE_NAME="${PREFIX}-export-listkeys"
POLICY_DEFINITION_NAME="${PREFIX}-activitylog"
ARM="https://management.azure.com"

TENANT_ID=""
CONFIG_APP_ID=""
AWS_ACCOUNT_ID=""
AWS_REGION=""
LOCATION=""
HUB_SUBSCRIPTION_ID=""
DRY_RUN=false

usage() {
    cat >&2 <<EOF
Usage: $0 --tenant-id <tenant-id> --config-app-id <app-id> \\
          --aws-account-id <account-id> --aws-region <aws-region> \\
          --location <azure-region> --hub-subscription-id <subscription-id> [options]

Required:
  --tenant-id <id>               Azure tenant and root management group ID
  --config-app-id <id>           Config application client ID from Script 1
  --aws-account-id <id>          12-digit AWS account that owns the connector
  --aws-region <region>          AWS Region of the connector, such as us-east-1
  --location <region>            Azure Region for newly created resources
  --hub-subscription-id <id>     Subscription that hosts a new Event Hub namespace

Options:
  --dry-run                      Validate access and show planned changes only
  -h, --help                     Show this help

The Config connector inventories every enabled subscription in the tenant that
its service principal can read. The --hub-subscription-id flag only selects where a new
Event Hub namespace is hosted; it does not limit collection scope.
EOF
    exit "${1:-1}"
}

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

log() {
    echo "[INFO] $1" >&2
}

warn() {
    echo "[WARN] $1" >&2
}

FAILED_SUBSCRIPTIONS_JSON='[]'
ALREADY_RUNNING_JSON='[]'

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}$ ]]
}

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

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

sha256_hex() {
    if command -v sha256sum >/dev/null 2>&1; then
        printf '%s' "$1" | sha256sum | cut -c1-64
    else
        printf '%s' "$1" | shasum -a 256 | cut -c1-64
    fi
}

json_equal() {
    [[ "$(printf '%s' "$1" | jq -cS .)" == "$(printf '%s' "$2" | jq -cS .)" ]]
}

parse_args() {
    while [[ $# -gt 0 ]]; do
        case "$1" in
            --tenant-id) require_value "$1" "${2:-}"; TENANT_ID="$2"; shift 2 ;;
            --config-app-id) require_value "$1" "${2:-}"; CONFIG_APP_ID="$2"; shift 2 ;;
            --aws-account-id) require_value "$1" "${2:-}"; AWS_ACCOUNT_ID="$2"; shift 2 ;;
            --aws-region) require_value "$1" "${2:-}"; AWS_REGION="$2"; shift 2 ;;
            --location) require_value "$1" "${2:-}"; LOCATION="$2"; shift 2 ;;
            --hub-subscription-id) require_value "$1" "${2:-}"; HUB_SUBSCRIPTION_ID="$2"; shift 2 ;;
            --dry-run) DRY_RUN=true; shift ;;
            -h|--help) usage 0 ;;
            *) echo "Error: unknown argument $1" >&2; usage ;;
        esac
    done
}

validate_args() {
    [[ -n "${TENANT_ID}" ]] || die "The --tenant-id flag is required."
    [[ -n "${CONFIG_APP_ID}" ]] || die "The --config-app-id flag is required."
    [[ -n "${AWS_ACCOUNT_ID}" ]] || die "The --aws-account-id flag is required."
    [[ -n "${AWS_REGION}" ]] || die "The --aws-region flag is required."
    [[ -n "${LOCATION}" ]] || die "The --location flag is required."
    [[ -n "${HUB_SUBSCRIPTION_ID}" ]] || die "The --hub-subscription-id flag is required."
    is_guid "${TENANT_ID}" || die "The --tenant-id flag must be a GUID."
    is_guid "${CONFIG_APP_ID}" || die "The --config-app-id flag must be a GUID."
    is_guid "${HUB_SUBSCRIPTION_ID}" || die "The --hub-subscription-id flag must be a GUID."
    [[ "${AWS_ACCOUNT_ID}" =~ ^[0-9]{12}$ ]] || die "The --aws-account-id flag must be 12 digits."
    [[ "${AWS_REGION}" =~ ^[a-z]{2,4}(-[a-z]+)+-[0-9]+$ ]] || die "Invalid --aws-region '${AWS_REGION}'."
    LOCATION=$(lower "${LOCATION}")
    [[ "${LOCATION}" =~ ^[a-z0-9]+$ ]] || die "Invalid --location '${LOCATION}'."
    TENANT_ID=$(lower "${TENANT_ID}")
    CONFIG_APP_ID=$(lower "${CONFIG_APP_ID}")
    HUB_SUBSCRIPTION_ID=$(lower "${HUB_SUBSCRIPTION_ID}")
}

derive_names() {
    local consumer_hash
    consumer_hash=$(sha256_hex "${TENANT_ID}|${AWS_ACCOUNT_ID}|${AWS_REGION}")
    CONSUMER="${AWS_ACCOUNT_ID}-${AWS_REGION}"
    DISCOVERY_TAG_KEY="AWSConfig-${CONSUMER}"
    MG_SCOPE="/providers/Microsoft.Management/managementGroups/${TENANT_ID}"
    RESOURCE_GROUP="${PREFIX}-${CONSUMER}"
    OWN_NAMESPACE_NAME="awscfg-${AWS_ACCOUNT_ID}-${consumer_hash:0:8}"
    OWN_NAMESPACE_ID="/subscriptions/${HUB_SUBSCRIPTION_ID}/resourceGroups/${RESOURCE_GROUP}/providers/Microsoft.EventHub/namespaces/${OWN_NAMESPACE_NAME}"
    ASSIGNMENT_NAME="awscfg-${consumer_hash:0:16}"
    ASSIGNMENT_ID="${MG_SCOPE}/providers/Microsoft.Authorization/policyAssignments/${ASSIGNMENT_NAME}"
    POLICY_DEFINITION_ID="${MG_SCOPE}/providers/Microsoft.Authorization/policyDefinitions/${POLICY_DEFINITION_NAME}"
    DEPLOYER_ROLE_RESOURCE_ID="${MG_SCOPE}/providers/Microsoft.Authorization/roleDefinitions/${DEPLOYER_ROLE_ID}"
    LIST_KEYS_ROLE_RESOURCE_ID="${MG_SCOPE}/providers/Microsoft.Authorization/roleDefinitions/${LIST_KEYS_ROLE_ID}"
    ACTIVITY_SETTING_NAME="${PREFIX}-activitylog-${consumer_hash:0:8}"
    ENTRA_SETTING_NAME="${PREFIX}-entra-audit-${consumer_hash:0:8}"
}

preflight_cli() {
    command -v jq >/dev/null 2>&1 || die "The jq command is required."
    command -v az >/dev/null 2>&1 || die "Azure CLI is required."
    local az_version signed_in_tenant
    az_version=$(az version --output json | jq -r '."azure-cli"') || die "Failed to read the Azure CLI version."
    version_at_least "${az_version}" "${MIN_AZ_VERSION}" ||
        die "Azure CLI ${MIN_AZ_VERSION} or newer is required (found ${az_version})."
    signed_in_tenant=$(az account show --query tenantId --output tsv 2>/dev/null) ||
        die "The Azure CLI is not signed in. Run 'az login --tenant ${TENANT_ID}' first."
    [[ "$(lower "${signed_in_tenant}")" == "${TENANT_ID}" ]] ||
        die "The Azure CLI is signed in to tenant '${signed_in_tenant}', not ${TENANT_ID}. Run 'az login --tenant ${TENANT_ID}'."
}

arm_get_optional() {
    local url="$1"
    shift
    local output error_code allowed_code
    if output=$(az rest --method get --url "${url}" --output json --only-show-errors 2>&1); then
        printf '%s' "${output}"
        return 0
    fi

    # Azure CLI 2.90 reports a failed read as `ERROR: Not Found({...})`, so read the code from
    # the JSON body first and fall back to the older `(Code) message` form.
    local body="${output#*\{}"
    body="{${body%\}*}}"
    error_code=$(printf '%s' "${body}" | jq -r '.error.code // .code // empty' 2>/dev/null || true)
    if [[ -z "${error_code}" && "${output}" =~ \(([A-Za-z][A-Za-z0-9.]*)\) ]]; then
        error_code="${BASH_REMATCH[1]}"
    fi
    for allowed_code in "$@"; do
        if [[ "${error_code}" == "${allowed_code}" ]]; then
            return 0
        fi
    done

    printf '%s\n' "${output}" >&2
    die "Failed to read ${url}${error_code:+ (Azure error code: ${error_code})}."
}

arm_put() {
    local url="$1"
    local body="$2"
    local description="$3"
    if [[ "${DRY_RUN}" == true ]]; then
        log "Would create ${description}."
        return 0
    fi
    az rest --method put --url "${url}" --body "${body}" --output none || die "Could not create ${description}."
    log "Created ${description}."
}

run_mutation() {
    local description="$1"
    shift
    if [[ "${DRY_RUN}" == true ]]; then
        log "Would create ${description}."
        return 0
    fi
    "$@" || die "Could not create ${description}."
    log "Created ${description}."
}

permission_allowed() {
    local permissions_json="$1"
    local desired
    desired=$(lower "$2")
    printf '%s' "${permissions_json}" | jq -e --arg desired "${desired}" '
        def glob($p): ($p | ascii_downcase | gsub("\\."; "\\.") | gsub("\\*"; ".*")) as $re
            | ($desired | test("^" + $re + "$"));
        any(.value[]; any(.actions[]?; glob(.)) and (any(.notActions[]?; glob(.)) | not))
    ' >/dev/null
}

effective_permissions() {
    local url="${ARM}$1/providers/Microsoft.Authorization/permissions?api-version=2022-04-01" page pages=""
    while [[ -n "${url}" ]]; do
        page=$(az rest --method get --url "${url}" --output json 2>/dev/null) || return 1
        url=$(printf '%s' "${page}" |
            jq -er 'if (.value | type) == "array" then .nextLink // "" else error end' 2>/dev/null) || return 1
        pages+="${page}"$'\n'
    done
    printf '%s' "${pages}" | jq -cs '{value:[.[].value[]]}'
}

missing_permissions_report() {
    local action place i role
    local roles=(
        "Owner, or Contributor"
        "Owner, or User Access Administrator"
        "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")
    local missing=("" "" "" "")
    while [[ $# -gt 0 ]]; do
        action="$1"
        place="$2"
        shift 2
        case "$(lower "${action}")" in
            microsoft.aadiam/*/read) role=3 ;;
            microsoft.aadiam/*) role=2 ;;
            microsoft.authorization/*/read) role=0 ;;
            microsoft.authorization/*) role=1 ;;
            *) role=0 ;;
        esac
        missing[role]+=$'\n'"    Missing '${action}' at ${place}."
    done
    for ((i = 0; i < ${#roles[@]}; i++)); do
        [[ -z "${missing[i]}" ]] || printf '%s' $'\n'"  ${roles[i]}, or a custom role with these actions:${missing[i]}"
    done
}

require_permissions() {
    local scopes=() scope_permissions=() missing=() report="" scope label action permissions cached i
    while [[ $# -gt 0 ]]; do
        scope="$1"
        label="$2"
        action="$3"
        shift 3
        cached=false
        for ((i = 0; i < ${#scopes[@]}; i++)); do
            if [[ "${scopes[i]}" == "${scope}" ]]; then
                permissions="${scope_permissions[i]}"
                cached=true
            fi
        done
        if [[ "${cached}" == false ]]; then
            if ! permissions=$(effective_permissions "${scope}"); then
                permissions=""
                report+=$'\n'"  Cannot inspect effective permissions at ${label} (${scope})."
            fi
            scopes+=("${scope}")
            scope_permissions+=("${permissions}")
        fi
        [[ -n "${permissions}" ]] || continue
        permission_allowed "${permissions}" "${action}" && continue
        missing+=("${action}" "${label} (${scope})")
    done
    [[ ${#missing[@]} -eq 0 ]] || report+=$(missing_permissions_report "${missing[@]}")
    [[ -z "${report}" ]] ||
        die "The signed-in account is missing Azure permissions this run needs. Nothing has been changed.${report}"
}

assign_role() {
    local principal_id="$1"
    local role="$2"
    local scope="$3"
    local description="$4"
    local attempt=1
    local error_output
    if [[ "${DRY_RUN}" == true ]]; then
        log "Would assign ${description}."
        return 0
    fi
    while true; do
        if error_output=$(az role assignment create \
            --assignee-object-id "${principal_id}" \
            --assignee-principal-type ServicePrincipal \
            --role "${role}" --scope "${scope}" --output none 2>&1); then
            log "Assigned ${description}."
            return 0
        fi
        if grep -Eqi 'already exists|RoleAssignmentExists' <<< "${error_output}"; then
            log "Adopted ${description}."
            return 0
        fi
        if grep -Eqi "PrincipalNotFound|RoleDefinitionDoesNotExist|doesn't exist" <<< "${error_output}" &&
            [[ ${attempt} -lt 12 ]]; then
            log "Identity or role propagation pending for ${description}; retrying in 10 seconds."
            attempt=$((attempt + 1))
            sleep 10
            continue
        fi
        printf '%s\n' "${error_output}" >&2
        die "Failed to assign ${description} at ${scope}."
    done
}

resolve_config_principal() {
    CONFIG_SP_OBJECT_ID=$(az ad sp show --id "${CONFIG_APP_ID}" --query id --output tsv 2>/dev/null) ||
        die "Could not find the Config service principal for ${CONFIG_APP_ID}. Run Script 1 first."
    is_guid "${CONFIG_SP_OBJECT_ID}" || die "Azure returned an invalid object ID for the Config service principal."
    local reader_count
    reader_count=$(az role assignment list --assignee "${CONFIG_SP_OBJECT_ID}" --scope "${MG_SCOPE}" \
        --query "[?ends_with(roleDefinitionId, '${READER_ROLE_ID}')] | length(@)" --output tsv) ||
        die "Failed to verify the Config service principal's tenant-root Reader role."
    [[ "${reader_count}" -ge 1 ]] ||
        die "The Config service principal does not have Reader at the tenant root management group. Run Script 1 first."
}

find_tagged_namespaces() {
    local body response
    body=$(jq -cn --arg key "${DISCOVERY_TAG_KEY}" '{
        query: ("resources | where type =~ \"microsoft.eventhub/namespaces\""
            + " | mv-expand bagexpansion=array tags"
            + " | where tostring(tags[0]) =~ \"" + $key + "\""
            + " | project id, name, hub = tostring(tags[1])"),
        options: {resultFormat: "objectArray"}
    }')
    response=$(az rest --method post \
        --url "${ARM}/providers/Microsoft.ResourceGraph/resources?api-version=2021-03-01" \
        --body "${body}" --output json) || die "Azure Resource Graph namespace discovery failed."
    [[ "$(printf '%s' "${response}" | jq -r '.resultTruncated // "false"')" == "false" ]] ||
        die "Azure Resource Graph returned an incomplete namespace result."
    printf '%s' "${response}" | jq -c '.data'
}

select_namespace() {
    local own tagged count
    own=$(arm_get_optional "${ARM}${OWN_NAMESPACE_ID}?api-version=2024-01-01" ResourceNotFound ResourceGroupNotFound)
    if [[ -n "${own}" ]]; then
        printf '%s' "${own}" | jq -e --arg consumer "${CONSUMER}" --arg key "${DISCOVERY_TAG_KEY}" \
            '.tags["aws-cloudwatch-config"] == $consumer and .tags[$key] == "activitylog"' >/dev/null ||
            die "Namespace ${OWN_NAMESPACE_NAME} exists but is not owned by ${CONSUMER}."
        NAMESPACE_ID="${OWN_NAMESPACE_ID}"
        NAMESPACE_EXISTS=true
        ADOPTED=false
        return
    fi
    tagged=$(find_tagged_namespaces)
    count=$(printf '%s' "${tagged}" | jq 'length')
    [[ "${count}" -le 1 ]] || die "More than one Event Hubs namespace has tag ${DISCOVERY_TAG_KEY}."
    if [[ "${count}" -eq 1 ]]; then
        NAMESPACE_ID=$(printf '%s' "${tagged}" | jq -r '.[0].id')
        EVENT_HUB_NAME=$(printf '%s' "${tagged}" | jq -r '.[0].hub')
        [[ -n "${EVENT_HUB_NAME}" && "${EVENT_HUB_NAME}" != "null" ]] ||
            die "The ${DISCOVERY_TAG_KEY} tag has no Event Hub name."
        NAMESPACE_EXISTS=true
        ADOPTED=true
        log "Adopting existing AWS Config Event Hubs namespace ${NAMESPACE_ID}."
        return
    fi
    NAMESPACE_ID="${OWN_NAMESPACE_ID}"
    NAMESPACE_EXISTS=false
    ADOPTED=false
}

ensure_own_namespace() {
    local resource_group_url resource_group tags
    tags=("aws-cloudwatch-config=${CONSUMER}")
    resource_group_url="${ARM}/subscriptions/${HUB_SUBSCRIPTION_ID}/resourceGroups/${RESOURCE_GROUP}?api-version=2021-04-01"
    resource_group=$(arm_get_optional "${resource_group_url}" ResourceGroupNotFound ResourceNotFound)
    if [[ -z "${resource_group}" ]]; then
        run_mutation "resource group ${RESOURCE_GROUP}" az group create \
            --name "${RESOURCE_GROUP}" --location "${LOCATION}" --subscription "${HUB_SUBSCRIPTION_ID}" \
            --tags "${tags[@]}" --only-show-errors --output none
    fi
    if [[ "${NAMESPACE_EXISTS}" == false ]]; then
        run_mutation "Event Hubs namespace ${OWN_NAMESPACE_NAME}" az eventhubs namespace create \
            --name "${OWN_NAMESPACE_NAME}" --resource-group "${RESOURCE_GROUP}" \
            --subscription "${HUB_SUBSCRIPTION_ID}" --location "${LOCATION}" \
            --sku "${EVENT_HUB_SKU}" --capacity "${EVENT_HUB_CAPACITY}" --min-tls 1.2 \
            --tags "${tags[@]}" "${DISCOVERY_TAG_KEY}=${EVENT_HUB_NAME}" \
            --only-show-errors --output none
    fi
}

# A diagnostic setting streams only to an event hub whose subscription is registered for
# Microsoft.Insights. This script does not register any resource providers, so the condition
# for the remediation's failure is explained.
ensure_insights_provider() {
    local subscription_id="$1" state
    state=$(az provider show --namespace Microsoft.Insights --subscription "${subscription_id}" \
        --query registrationState --output tsv --only-show-errors) ||
        die "Failed to read the Microsoft.Insights registration of subscription ${subscription_id}."
    [[ "${state}" == "Registered" ]] ||
        die "Subscription ${subscription_id} is not registered to use Microsoft.Insights. This script does not perform registration. You can register it with the following command, and re-run the script: az provider register --namespace Microsoft.Insights --subscription ${subscription_id} --wait"
}

ensure_event_hub() {
    local hub_id existing=""
    hub_id="${NAMESPACE_ID}/eventhubs/${EVENT_HUB_NAME}"
    if [[ "${DRY_RUN}" != true || "${NAMESPACE_EXISTS}" == true ]]; then
        existing=$(arm_get_optional "${ARM}${hub_id}?api-version=2024-01-01" ResourceNotFound EntityNotFound)
    fi
    if [[ -n "${existing}" ]]; then
        log "Adopted Event Hub ${EVENT_HUB_NAME}."
    elif [[ "${ADOPTED}" == true ]]; then
        die "The tagged namespace points to Event Hub '${EVENT_HUB_NAME}', but that hub does not exist."
    else
        arm_put "${ARM}${hub_id}?api-version=2024-01-01" "$(jq -cn \
            --argjson partitions "${EVENT_HUB_PARTITION_COUNT}" \
            --argjson hours "${EVENT_HUB_RETENTION_HOURS}" \
            '{properties:{partitionCount:$partitions,retentionDescription:{cleanupPolicy:"Delete",retentionTimeInHours:$hours}}}')" \
            "Event Hub ${EVENT_HUB_NAME}"
    fi
}

ensure_consumer_group() {
    local group_id existing=""
    group_id="${NAMESPACE_ID}/eventhubs/${EVENT_HUB_NAME}/consumergroups/${CONSUMER_GROUP_NAME}"
    if [[ "${DRY_RUN}" != true || "${NAMESPACE_EXISTS}" == true ]]; then
        existing=$(arm_get_optional "${ARM}${group_id}?api-version=2024-01-01" ResourceNotFound ConsumerGroupNotFound)
    fi
    if [[ -n "${existing}" ]]; then
        log "Adopted consumer group ${CONSUMER_GROUP_NAME}."
    else
        arm_put "${ARM}${group_id}?api-version=2024-01-01" '{"properties":{}}' \
            "consumer group ${CONSUMER_GROUP_NAME}"
    fi
}

adoptable_export_rule_exists() {
    local existing
    existing=$(arm_get_optional "${ARM}${EXPORT_RULE_ID}?api-version=2024-01-01" \
        ResourceNotFound AuthorizationRuleNotFound) || exit 1
    [[ -n "${existing}" ]] || return 1
    printf '%s' "${existing}" | jq -e '(.properties.rights | sort) == ["Listen","Manage","Send"]' >/dev/null ||
        die "Authorization rule ${EXPORT_RULE_NAME} exists with different rights."
}

ensure_export_rule() {
    if [[ "${DRY_RUN}" != true || "${NAMESPACE_EXISTS}" == true ]] && adoptable_export_rule_exists; then
        log "Adopted authorization rule ${EXPORT_RULE_NAME}."
    else
        arm_put "${ARM}${EXPORT_RULE_ID}?api-version=2024-01-01" \
            '{"properties":{"rights":["Manage","Send","Listen"]}}' "authorization rule ${EXPORT_RULE_NAME}"
    fi
}

namespace_export_exists() {
    local settings="$1"
    local category="$2"
    [[ -n "${settings}" ]] || return 1
    printf '%s' "${settings}" | jq -e \
        --arg namespace "$(lower "${NAMESPACE_ID}")/authorizationrules/" \
        --arg hub "$(lower "${EVENT_HUB_NAME}")" --arg category "${category}" '
        any(.value[]?;
            ((.properties.eventHubAuthorizationRuleId // "") | ascii_downcase | startswith($namespace))
            and ((.properties.eventHubName // "") | ascii_downcase) == $hub
            and any(.properties.logs[]?; .category == $category and .enabled == true))
    ' >/dev/null
}

setting_names() {
    printf '%s' "$1" | jq -r '.value | map(.name // "(unnamed)") | join(", ")'
}

admit_subscription_for_remediation() {
    local subscription="$1"
    local settings error
    if ! settings=$(az rest --method get \
        --url "${ARM}/subscriptions/${subscription}/providers/Microsoft.Insights/diagnosticSettings?api-version=2021-05-01-preview" \
        --output json --only-show-errors 2>&1); then
        error="Failed to read the subscription's diagnostic settings: ${settings}"
    elif ! printf '%s' "${settings}" | jq -e '(.value | type) == "array"' >/dev/null 2>&1; then
        error="Azure returned an invalid diagnostic-setting list for the subscription."
    elif namespace_export_exists "${settings}" Administrative ||
        printf '%s' "${settings}" | jq -e --arg name "$(lower "${ACTIVITY_SETTING_NAME}")" '
            (.value | length) < 5 or any(.value[]; ((.name // "") | ascii_downcase) == $name)' >/dev/null 2>&1; then
        return 0
    else
        error="No free diagnostic setting slot for the AWS Config Activity Log export (Azure allows 5 per subscription): $(setting_names "${settings}"). This script requires an available diagnostic setting in this subscription."
    fi
    warn "Skipped remediation for subscription ${subscription}: $(lower "${error:0:1}")${error:1}"
    FAILED_SUBSCRIPTIONS_JSON=$(printf '%s' "${FAILED_SUBSCRIPTIONS_JSON}" | jq -c \
        --arg sub "${subscription}" --arg err "${error}" \
        '. + [{subscriptionId:$sub,error:$err}]')
    return 1
}

withhold_remediation_without_setting_slot() {
    local subscription active_name plan='[]'
    while IFS=$'\t' read -r subscription active_name; do
        [[ -n "${active_name}" ]] || admit_subscription_for_remediation "${subscription}" || continue
        plan=$(printf '%s' "${plan}" | jq -c --arg subscriptionId "${subscription}" \
            --arg activeName "${active_name}" '. + [{subscriptionId:$subscriptionId,activeName:$activeName}]')
    done < <(printf '%s' "${REMEDIATION_PLAN_JSON}" | jq -r '.[] | [.subscriptionId,.activeName] | @tsv')
    REMEDIATION_PLAN_JSON="${plan}"
}

require_entra_setting_slot() {
    local settings="$1"
    local own_setting
    [[ -n "${settings}" ]] || return 0
    own_setting=$(printf '%s' "${settings}" | jq -c --arg name "$(lower "${ENTRA_SETTING_NAME}")" '
        first(.value[] | select(((.name // "") | ascii_downcase) == $name)) // empty')
    adoptable_entra_setting_exists "${own_setting}" ||
        printf '%s' "${settings}" | jq -e '(.value | length) < 5' >/dev/null ||
        die "Microsoft Entra ID has no free diagnostic setting slot for the AWS Config audit log export (Azure allows 5 per tenant): $(setting_names "${settings}"). Nothing has been changed. This script requires an available Microsoft Entra diagnostic setting."
}

find_foreign_activity_policy() {
    local assignments matches count
    assignments=$(arm_get_optional \
        "${ARM}${MG_SCOPE}/providers/Microsoft.Authorization/policyAssignments?api-version=2022-06-01&\$filter=atScope()" \
        ResourceNotFound) || exit 1
    [[ -n "${assignments}" ]] || return 0
    matches=$(printf '%s' "${assignments}" | jq -c \
        --arg namespace "$(lower "${NAMESPACE_ID}")/" --arg own "$(lower "${ASSIGNMENT_NAME}")" '
        [.value[]? | select(
            (.name | ascii_downcase) != $own
            and ((.properties.parameters // {}) | tostring | ascii_downcase | contains($namespace)))]')
    count=$(printf '%s' "${matches}" | jq 'length')
    [[ "${count}" -le 1 ]] || die "More than one tenant-root policy assignment exports Activity Logs to this namespace."
    [[ "${count}" -eq 1 ]] && printf '%s' "${matches}" | jq -r '.[0].id'
    return 0
}

role_body() {
    local name="$1"
    local description="$2"
    local actions="$3"
    jq -cn --arg name "${name}" --arg description "${description}" \
        --arg scope "${MG_SCOPE}" --argjson actions "${actions}" '{
        properties:{roleName:$name,description:$description,type:"CustomRole",
            permissions:[{actions:$actions,notActions:[],dataActions:[],notDataActions:[]}],assignableScopes:[$scope]}}'
}

role_projection() {
    jq -cS '{name:.properties.roleName,
        actions:([.properties.permissions[].actions[]?] | map(ascii_downcase) | sort),
        notActions:([.properties.permissions[].notActions[]?] | map(ascii_downcase) | sort),
        dataActions:([.properties.permissions[].dataActions[]?] | map(ascii_downcase) | sort),
        notDataActions:([.properties.permissions[].notDataActions[]?] | map(ascii_downcase) | sort),
        scopes:(.properties.assignableScopes | map(ascii_downcase) | sort)}'
}

deployer_role_body() {
    role_body "${DEPLOYER_ROLE_NAME}" \
        "Deploy subscription Activity Log diagnostic settings for AWS Config." \
        '["Microsoft.Insights/diagnosticSettings/read","Microsoft.Insights/diagnosticSettings/write",
          "Microsoft.Resources/deployments/read","Microsoft.Resources/deployments/write",
          "Microsoft.Resources/deployments/operations/read","Microsoft.Resources/deployments/operationStatuses/read",
          "Microsoft.Resources/deployments/validate/action"]'
}

list_keys_role_body() {
    role_body "${LIST_KEYS_ROLE_NAME}" \
        "Reference the AWS Config Event Hub authorization rule from a diagnostic setting." \
        '["Microsoft.EventHub/namespaces/authorizationRules/read",
          "Microsoft.EventHub/namespaces/authorizationRules/listKeys/action"]'
}

adoptable_custom_role_exists() {
    local resource_id="$1"
    local body="$2"
    local name="$3"
    local existing
    existing=$(arm_get_optional "${ARM}${resource_id}?api-version=2022-04-01" \
        ResourceNotFound RoleDefinitionDoesNotExist) || exit 1
    [[ -n "${existing}" ]] || return 1
    json_equal "$(printf '%s' "${existing}" | role_projection)" "$(printf '%s' "${body}" | role_projection)" ||
        die "Custom role ${name} exists with a different definition."
}

ensure_custom_role() {
    local resource_id="$1"
    local body="$2"
    local name="$3"
    if adoptable_custom_role_exists "${resource_id}" "${body}" "${name}"; then
        log "Adopted custom role ${name}."
    else
        arm_put "${ARM}${resource_id}?api-version=2022-04-01" "${body}" "custom role ${name}"
    fi
}

ensure_custom_roles() {
    local deployer_body list_keys_body
    deployer_body=$(deployer_role_body)
    list_keys_body=$(list_keys_role_body)
    ensure_custom_role "${DEPLOYER_ROLE_RESOURCE_ID}" "${deployer_body}" "${DEPLOYER_ROLE_NAME}"
    ensure_custom_role "${LIST_KEYS_ROLE_RESOURCE_ID}" "${list_keys_body}" "${LIST_KEYS_ROLE_NAME}"
}

policy_rule() {
    cat <<'JSON' | jq -c --arg deployer "${DEPLOYER_ROLE_RESOURCE_ID}" --arg keys "${LIST_KEYS_ROLE_RESOURCE_ID}" \
        '.then.details.roleDefinitionIds = [$deployer, $keys]'
{
  "if": {"field": "type", "equals": "Microsoft.Resources/subscriptions"},
  "then": {
    "effect": "[parameters('effect')]",
    "details": {
      "type": "Microsoft.Insights/diagnosticSettings",
      "deploymentScope": "subscription",
      "existenceScope": "subscription",
      "existenceCondition": {"allOf": [
        {"field": "Microsoft.Insights/diagnosticSettings/eventHubAuthorizationRuleId", "like": "[concat(parameters('namespaceId'), '/authorizationRules/*')]"},
        {"field": "Microsoft.Insights/diagnosticSettings/eventHubName", "equals": "[parameters('eventHubName')]"},
        {"count": {"field": "Microsoft.Insights/diagnosticSettings/logs[*]", "where": {"allOf": [
          {"field": "Microsoft.Insights/diagnosticSettings/logs[*].category", "equals": "Administrative"},
          {"field": "Microsoft.Insights/diagnosticSettings/logs[*].enabled", "equals": "true"}
        ]}}, "greater": 0}
      ]},
      "roleDefinitionIds": [],
      "deployment": {
        "location": "eastus",
        "properties": {
          "mode": "incremental",
          "template": {
            "$schema": "https://schema.management.azure.com/schemas/2018-05-01/subscriptionDeploymentTemplate.json#",
            "contentVersion": "1.0.0.0",
            "parameters": {
              "eventHubAuthorizationRuleId": {"type": "string"},
              "eventHubName": {"type": "string"},
              "profileName": {"type": "string"}
            },
            "resources": [{
              "type": "Microsoft.Insights/diagnosticSettings",
              "apiVersion": "2021-05-01-preview",
              "name": "[parameters('profileName')]",
              "properties": {
                "eventHubAuthorizationRuleId": "[parameters('eventHubAuthorizationRuleId')]",
                "eventHubName": "[parameters('eventHubName')]",
                "logs": [{"category": "Administrative", "enabled": true}]
              }
            }]
          },
          "parameters": {
            "eventHubAuthorizationRuleId": {"value": "[parameters('eventHubAuthorizationRuleId')]"},
            "eventHubName": {"value": "[parameters('eventHubName')]"},
            "profileName": {"value": "[parameters('profileName')]"}
          }
        }
      }
    }
  }
}
JSON
}

policy_definition_body() {
    jq -cn --argjson rule "$(policy_rule)" --arg version "${POLICY_VERSION}" '{
        properties:{
            displayName:"AWS Config: export Activity Logs to the AWS Config Event Hub",
            description:"Adds an Administrative Activity Log diagnostic setting to each subscription.",
            policyType:"Custom",mode:"All",
            metadata:{category:"Monitoring",awsCloudWatchConfigManaged:true,awsCloudWatchConfigPolicyVersion:$version},
            parameters:{
                effect:{type:"String",defaultValue:"DeployIfNotExists",allowedValues:["DeployIfNotExists","Disabled"]},
                eventHubAuthorizationRuleId:{type:"String"},namespaceId:{type:"String"},
                eventHubName:{type:"String"},profileName:{type:"String"}},
            policyRule:$rule}}'
}

adoptable_policy_definition_exists() {
    local body="$1"
    local existing
    existing=$(arm_get_optional "${ARM}${POLICY_DEFINITION_ID}?api-version=2021-06-01" \
        ResourceNotFound PolicyDefinitionNotFound) || exit 1
    [[ -n "${existing}" ]] || return 1
    json_equal \
        "$(printf '%s' "${existing}" | jq -cS '{rule:.properties.policyRule,parameters:.properties.parameters,mode:.properties.mode,version:.properties.metadata.awsCloudWatchConfigPolicyVersion}')" \
        "$(printf '%s' "${body}" | jq -cS '{rule:.properties.policyRule,parameters:.properties.parameters,mode:.properties.mode,version:.properties.metadata.awsCloudWatchConfigPolicyVersion}')" ||
        die "Policy definition ${POLICY_DEFINITION_NAME} differs from the expected version ${POLICY_VERSION} or content."
}

ensure_policy_definition() {
    local body
    body=$(policy_definition_body)
    if adoptable_policy_definition_exists "${body}"; then
        log "Adopted policy definition ${POLICY_DEFINITION_NAME}."
    else
        arm_put "${ARM}${POLICY_DEFINITION_ID}?api-version=2021-06-01" "${body}" \
            "policy definition ${POLICY_DEFINITION_NAME}"
    fi
}

require_adoptable_shared_definitions() {
    local deployer_body list_keys_body policy_body
    deployer_body=$(deployer_role_body)
    list_keys_body=$(list_keys_role_body)
    policy_body=$(policy_definition_body)
    adoptable_custom_role_exists "${DEPLOYER_ROLE_RESOURCE_ID}" "${deployer_body}" "${DEPLOYER_ROLE_NAME}" || true
    adoptable_custom_role_exists "${LIST_KEYS_ROLE_RESOURCE_ID}" "${list_keys_body}" "${LIST_KEYS_ROLE_NAME}" || true
    adoptable_policy_definition_exists "${policy_body}" || true
}

policy_assignment_body() {
    jq -cn --arg location "${LOCATION}" --arg definition "${POLICY_DEFINITION_ID}" \
        --arg consumer "${CONSUMER}" --arg rule "${EXPORT_RULE_ID}" --arg namespace "${NAMESPACE_ID}" \
        --arg hub "${EVENT_HUB_NAME}" --arg setting "${ACTIVITY_SETTING_NAME}" '{
        location:$location,identity:{type:"SystemAssigned"},properties:{
            displayName:("AWS Config Activity Log export (" + $consumer + ")"),
            policyDefinitionId:$definition,enforcementMode:"Default",
            metadata:{awsCloudWatchConfigManaged:true,awsCloudWatchConfigConsumer:$consumer},
            parameters:{eventHubAuthorizationRuleId:{value:$rule},namespaceId:{value:$namespace},
                eventHubName:{value:$hub},profileName:{value:$setting}}}}'
}

adoptable_policy_assignment() {
    local body existing
    body=$(policy_assignment_body)
    existing=$(arm_get_optional "${ARM}${ASSIGNMENT_ID}?api-version=2022-06-01" \
        ResourceNotFound PolicyAssignmentNotFound) || exit 1
    [[ -n "${existing}" ]] || return 0
    jq -e -n --argjson actual "${existing}" --argjson expected "${body}" '
        def norm:
            if type == "object" then with_entries(.value |= norm)
            elif type == "array" then map(norm)
            elif type == "string" then ascii_downcase
            else . end;
        ($actual.properties.policyDefinitionId | ascii_downcase) == ($expected.properties.policyDefinitionId | ascii_downcase)
        and ($actual.properties.parameters | norm) == ($expected.properties.parameters | norm)
        and (($actual.properties.enforcementMode // "Default") == ($expected.properties.enforcementMode // "Default"))
        and $actual.identity.type == "SystemAssigned"' >/dev/null ||
        die "Policy assignment ${ASSIGNMENT_NAME} exists with different settings."
    printf '%s' "${existing}"
}

ensure_policy_assignment() {
    local body existing response principal_id
    body=$(policy_assignment_body)
    existing=$(adoptable_policy_assignment) || exit 1
    if [[ -n "${existing}" ]]; then
        principal_id=$(printf '%s' "${existing}" | jq -r '.identity.principalId')
        log "Adopted policy assignment ${ASSIGNMENT_NAME}."
    elif [[ "${DRY_RUN}" == true ]]; then
        log "Would create policy assignment ${ASSIGNMENT_NAME} at the tenant root management group."
        return 0
    else
        response=$(az rest --method put --url "${ARM}${ASSIGNMENT_ID}?api-version=2022-06-01" \
            --body "${body}" --output json) || die "Could not create policy assignment ${ASSIGNMENT_NAME}."
        principal_id=$(printf '%s' "${response}" | jq -r '.identity.principalId')
        log "Created policy assignment ${ASSIGNMENT_NAME}."
    fi
    is_guid "${principal_id}" || die "Policy assignment ${ASSIGNMENT_NAME} has no system-assigned identity."
    assign_role "${principal_id}" "${DEPLOYER_ROLE_ID}" "${MG_SCOPE}" \
        "${DEPLOYER_ROLE_NAME} to the policy identity at the tenant root management group"
    assign_role "${principal_id}" "${LIST_KEYS_ROLE_ID}" "${EXPORT_RULE_ID}" \
        "${LIST_KEYS_ROLE_NAME} to the policy identity on ${EXPORT_RULE_NAME}"
}

ensure_activity_log_policy() {
    ensure_custom_roles
    ensure_policy_definition
    ensure_policy_assignment
}

adoptable_entra_setting_exists() {
    local setting="$1"
    [[ -n "${setting}" ]] || return 1
    printf '%s' "${setting}" | jq -e \
        --arg rule "$(lower "${EXPORT_RULE_ID}")" --arg hub "$(lower "${EVENT_HUB_NAME}")" '
        ((.properties.eventHubAuthorizationRuleId // "") | ascii_downcase) == $rule
        and ((.properties.eventHubName // "") | ascii_downcase) == $hub
        and any(.properties.logs[]?; .category == "AuditLogs" and .enabled == true)
    ' >/dev/null ||
        die "Entra diagnostic setting ${ENTRA_SETTING_NAME} has different settings."
}

ensure_entra_export() {
    local url existing
    url="${ARM}/providers/microsoft.aadiam/diagnosticSettings/${ENTRA_SETTING_NAME}?api-version=2017-04-01"
    existing=$(arm_get_optional "${url}" ResourceNotFound)
    if adoptable_entra_setting_exists "${existing}"; then
        log "Adopted Entra ID AuditLogs diagnostic setting ${ENTRA_SETTING_NAME}."
    else
        arm_put "${url}" "$(jq -cn --arg rule "${EXPORT_RULE_ID}" --arg hub "${EVENT_HUB_NAME}" '{
            properties:{eventHubAuthorizationRuleId:$rule,eventHubName:$hub,
                logs:[{category:"AuditLogs",enabled:true,retentionPolicy:{enabled:false,days:0}}]}}')" \
            "Entra ID AuditLogs diagnostic setting ${ENTRA_SETTING_NAME}"
    fi
}

collect_subscription_snapshot() {
    local entities_json accounts_json entity_ids missing missing_list missing_count disabled_count invalid accounts_ok=true
    log "Discovering subscriptions under tenant ${TENANT_ID}."
    entities_json=$(az account management-group entities list \
        --query "[?type=='/subscriptions'].{id:name,type:type}" --output json) ||
        die "Failed to list subscriptions under tenant root management group ${TENANT_ID}."
    printf '%s' "${entities_json}" | jq -e 'type == "array"' >/dev/null ||
        die "Azure returned an invalid management-group subscription list."
    invalid=$(printf '%s' "${entities_json}" | jq -r '.[].id' | grep -Ev \
        '^[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}$' | head -n 1 || true)
    [[ -z "${invalid}" ]] || die "The value '${invalid}' is not a GUID subscription ID."
    entity_ids=$(printf '%s' "${entities_json}" | jq -c '[.[].id | ascii_downcase] | unique | sort')
    if [[ "$(printf '%s' "${entity_ids}" | jq 'length')" -eq 0 ]]; then
        warn "No subscriptions were found under tenant root management group ${TENANT_ID}; this target still appears in the result with an empty subscriptionIds list."
        SUBSCRIPTION_IDS_JSON='[]'
        return
    fi

    if ! accounts_json=$(az account list --all --refresh --output json); then
        warn "Failed to read subscription states from Azure CLI; submitting remediation for every discovered subscription, including any disabled ones."
        accounts_ok=false
    fi

    if [[ "${accounts_ok}" == false ]]; then
        SUBSCRIPTION_IDS_JSON="${entity_ids}"
    else
        printf '%s' "${accounts_json}" | jq -e 'type == "array"' >/dev/null ||
            die "Azure CLI returned an invalid subscription-state list."
        missing_list=$(jq -cn --argjson entities "${entity_ids}" --argjson accounts "${accounts_json}" \
            --arg tenant "${TENANT_ID}" '
            ($accounts | map(select((.tenantId // "" | ascii_downcase) == $tenant))
                | map((.id // "") | ascii_downcase)) as $visible
            | [$entities[] as $entity | select($visible | index($entity) | not) | $entity]')
        missing_count=$(printf '%s' "${missing_list}" | jq 'length')
        missing=$(printf '%s' "${missing_list}" | jq -r 'join(", ")')
        [[ "${missing_count}" -eq 0 ]] ||
            warn "Could not read ${missing_count} subscription(s) under tenant ${TENANT_ID}: ${missing}. Not visible to this sign-in, so not submitted for remediation. If you have access to every subscription in the tenant, signing in with it and re-running this script lets it remediate them."

        disabled_count=$(jq -rn --argjson entities "${entity_ids}" --argjson accounts "${accounts_json}" \
            --arg tenant "${TENANT_ID}" '
            ($accounts | map(select((.tenantId // "" | ascii_downcase) == $tenant))
                | map(select((.state // "") != "Enabled"))
                | map((.id // "") | ascii_downcase)) as $non_enabled
            | [$entities[] as $entity | select($non_enabled | index($entity))] | length')
        [[ "${disabled_count}" -eq 0 ]] ||
            log "Skipping ${disabled_count} subscription(s) not in an Enabled state under tenant ${TENANT_ID}; not remediation targets."

        SUBSCRIPTION_IDS_JSON=$(jq -cn --argjson entities "${entity_ids}" --argjson accounts "${accounts_json}" \
            --arg tenant "${TENANT_ID}" '
            [$accounts[]
                | select((.tenantId // "" | ascii_downcase) == $tenant)
                | select((.state // "") == "Enabled")
                | (.id | ascii_downcase)
                | select($entities | index(.))] | unique | sort')
    fi
    [[ "$(printf '%s' "${SUBSCRIPTION_IDS_JSON}" | jq 'length')" -gt 0 ]] ||
        warn "No enabled subscriptions to remediate under tenant ${TENANT_ID}; this target still appears in the result with an empty subscriptionIds list."
}

validate_remediation_snapshot() {
    local assignment_id_lower assignment_prefix assignment_name
    assignment_id_lower=$(lower "${ASSIGNMENT_ID}")
    assignment_prefix=$(lower "${MG_SCOPE}/providers/Microsoft.Authorization/policyAssignments/")
    case "${assignment_id_lower}" in
        "${assignment_prefix}"*) ;;
        *) die "Policy assignment ID '${ASSIGNMENT_ID}' is not a full tenant-root assignment resource ID." ;;
    esac
    assignment_name="${assignment_id_lower#"${assignment_prefix}"}"
    [[ -n "${assignment_name}" && "${assignment_name}" != */* ]] ||
        die "Policy assignment ID '${ASSIGNMENT_ID}' is not a full tenant-root assignment resource ID."
    printf '%s' "${SUBSCRIPTION_IDS_JSON}" | jq -e '
        type == "array" and
        all(.[]; test("^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$"))
    ' >/dev/null || die "The remediation subscription snapshot is invalid."
    REMEDIATION_TARGETS_JSON=$(jq -cn --arg assignment "${ASSIGNMENT_ID}" \
        --argjson subscriptions "${SUBSCRIPTION_IDS_JSON}" \
        '[{policyAssignmentId:$assignment,tenantWide:true,subscriptionIds:$subscriptions}]')
}

prepare_remediation_plan() {
    local subscription tasks active_name plan='[]'
    while IFS= read -r subscription; do
        if ! tasks=$(az policy remediation list --subscription "${subscription}" \
            --only-show-errors --output json 2>&1); then
            warn "Failed to check for an in-progress remediation for subscription ${subscription}: ${tasks}"
            FAILED_SUBSCRIPTIONS_JSON=$(printf '%s' "${FAILED_SUBSCRIPTIONS_JSON}" | jq -c \
                --arg sub "${subscription}" --arg err "${tasks}" \
                '. + [{subscriptionId:$sub,error:$err}]')
            continue
        fi
        if ! printf '%s' "${tasks}" | jq -e 'type == "array"' >/dev/null; then
            warn "Failed to check for an in-progress remediation for subscription ${subscription}: invalid remediation task list response"
            FAILED_SUBSCRIPTIONS_JSON=$(printf '%s' "${FAILED_SUBSCRIPTIONS_JSON}" | jq -c \
                --arg sub "${subscription}" --arg err "invalid remediation task list response" \
                '. + [{subscriptionId:$sub,error:$err}]')
            continue
        fi
        active_name=$(printf '%s' "${tasks}" | jq -r --arg assignment "$(lower "${ASSIGNMENT_ID}")" '
            [.[] | select(
                ((.policyAssignmentId // "") | ascii_downcase) == $assignment
                and (
                    ((.provisioningState // "") | ascii_downcase) == "accepted"
                    or ((.provisioningState // "") | ascii_downcase) == "evaluating"
                    or ((.provisioningState // "") | ascii_downcase) == "running"
                    or ((.provisioningState // "") | ascii_downcase) == "inprogress"
                ))]
            | .[0].name // empty')
        plan=$(printf '%s' "${plan}" | jq -c --arg subscriptionId "${subscription}" \
            --arg activeName "${active_name}" '. + [{subscriptionId:$subscriptionId,activeName:$activeName}]')
    done < <(printf '%s' "${SUBSCRIPTION_IDS_JSON}" | jq -r '.[]')
    REMEDIATION_PLAN_JSON="${plan}"
}

submit_remediation_tasks() {
    local subscription active_name remediation_name started=0 adopted=0 total error_output
    total=$(printf '%s' "${REMEDIATION_PLAN_JSON}" | jq 'length')
    [[ "${SUPPRESS_REMEDIATION_SUMMARY:-false}" == true ]] ||
        log "Checking remediation status for ${total} existing enabled subscription(s)."
    while IFS=$'\t' read -r subscription active_name; do
        if [[ -n "${active_name}" ]]; then
            adopted=$((adopted + 1))
            log "Remediation ${active_name} is already running for subscription ${subscription}."
            ALREADY_RUNNING_JSON=$(printf '%s' "${ALREADY_RUNNING_JSON}" | jq -c \
                --arg sub "${subscription}" --arg name "${active_name}" \
                '. + [{subscriptionId:$sub,remediationName:$name}]')
            continue
        fi
        remediation_name="aws-cloudwatch-remediation-${subscription:0:8}-$(date +%s)-${RANDOM}"
        if error_output=$(az policy remediation create \
            --name "${remediation_name}" \
            --subscription "${subscription}" \
            --policy-assignment "${ASSIGNMENT_ID}" \
            --resource-discovery-mode ReEvaluateCompliance \
            --only-show-errors --output none 2>&1); then
            started=$((started + 1))
            log "Started remediation ${remediation_name} for subscription ${subscription}."
        else
            warn "Failed to submit remediation task ${remediation_name} for subscription ${subscription}: ${error_output}"
            FAILED_SUBSCRIPTIONS_JSON=$(printf '%s' "${FAILED_SUBSCRIPTIONS_JSON}" | jq -c \
                --arg sub "${subscription}" --arg err "${error_output}" \
                '. + [{subscriptionId:$sub,error:$err}]')
        fi
    done < <(printf '%s' "${REMEDIATION_PLAN_JSON}" | jq -r '.[] | [.subscriptionId,.activeName] | @tsv')
    [[ "${SUPPRESS_REMEDIATION_SUMMARY:-false}" == true ]] && return 0
    log "Started ${started} remediation tasks successfully."
    [[ "${adopted}" -eq 0 ]] || log "Kept ${adopted} existing remediation tasks running."
    [[ "$((started + adopted))" -eq 0 ]] || log "Check a remediation's status with: az policy remediation show --name <name> --subscription <subscription-id>, using the name and subscription logged."
    log "Remediation runs asynchronously. Monitor progress in Azure Policy > Remediation."
}

print_result() {
    local jq_flags=(-nM)
    [[ -t 1 ]] || jq_flags+=(-c)
    jq "${jq_flags[@]}" --arg namespaceId "${NAMESPACE_ID}" --arg eventHubName "${EVENT_HUB_NAME}" \
        --arg consumerGroup "${CONSUMER_GROUP_NAME}" --arg discoveryTag "${DISCOVERY_TAG_KEY}" \
        --argjson adopted "${ADOPTED}" --argjson remediationTargets "${REMEDIATION_TARGETS_JSON}" \
        --argjson failedSubscriptions "${FAILED_SUBSCRIPTIONS_JSON}" \
        --argjson alreadyRunning "${ALREADY_RUNNING_JSON}" \
        '{namespaceId:$namespaceId,eventHubName:$eventHubName,consumerGroup:$consumerGroup,
          discoveryTag:$discoveryTag,adopted:$adopted,
          remediationTargets:[$remediationTargets[] | . + {failedSubscriptions:$failedSubscriptions, alreadyRunning:$alreadyRunning}]}'
}

require_lookup_permissions() {
    local mg_label="tenant root management group" entra_permissions
    local checks=(
        "${MG_SCOPE}" "${mg_label}" "Microsoft.Authorization/roleAssignments/read"
        "${MG_SCOPE}" "${mg_label}" "Microsoft.Authorization/policyAssignments/read"
        "${MG_SCOPE}" "${mg_label}" "Microsoft.EventHub/namespaces/read"
        "${MG_SCOPE}" "${mg_label}" "Microsoft.Resources/subscriptions/read"
        "/subscriptions/${HUB_SUBSCRIPTION_ID}" "infrastructure subscription" "Microsoft.EventHub/namespaces/read"
        "/providers/microsoft.aadiam" "Microsoft Entra ID" "microsoft.aadiam/diagnosticSettings/read")
    if entra_permissions=$(effective_permissions "/providers/microsoft.aadiam") &&
        ! permission_allowed "${entra_permissions}" "microsoft.aadiam/diagnosticSettings/read"; then
        checks+=("/providers/microsoft.aadiam" "Microsoft Entra ID" "microsoft.aadiam/diagnosticSettings/write")
    fi
    require_permissions "${checks[@]}"
}

require_setup_permissions() {
    local needs_entra="$1"
    local foreign_assignment="$2"
    local uses_export_rule="$3"
    local hub_scope="/subscriptions/${HUB_SUBSCRIPTION_ID}"
    local hub_label="infrastructure subscription"
    local namespace_scope="${NAMESPACE_ID}"
    local namespace_label="Event Hubs namespace"
    local checks=() reads_namespace_children=true
    [[ "${DRY_RUN}" == true && "${NAMESPACE_EXISTS}" == false ]] && reads_namespace_children=false
    if [[ "${NAMESPACE_EXISTS}" == false ]]; then
        namespace_scope="${hub_scope}"
        namespace_label="${hub_label}"
        checks+=(
            "${hub_scope}" "${hub_label}" "Microsoft.Resources/subscriptions/resourceGroups/write"
            "${hub_scope}" "${hub_label}" "Microsoft.EventHub/namespaces/write")
    fi
    [[ "${ADOPTED}" == true ]] ||
        checks+=(
            "${hub_scope}" "${hub_label}" "Microsoft.Resources/subscriptions/resourceGroups/read"
            "${namespace_scope}" "${namespace_label}" "Microsoft.EventHub/namespaces/eventhubs/write")
    checks+=(
        "${namespace_scope}" "${namespace_label}" "Microsoft.EventHub/namespaces/eventhubs/consumergroups/write"
        "${namespace_scope}" "${namespace_label}" "Microsoft.Authorization/roleAssignments/write")
    [[ "${reads_namespace_children}" == false ]] ||
        checks+=(
            "${namespace_scope}" "${namespace_label}" "Microsoft.EventHub/namespaces/eventhubs/read"
            "${namespace_scope}" "${namespace_label}" "Microsoft.EventHub/namespaces/eventhubs/consumergroups/read")
    if [[ "${uses_export_rule}" == true ]]; then
        checks+=("${namespace_scope}" "${namespace_label}" "Microsoft.EventHub/namespaces/authorizationRules/write")
        [[ "${reads_namespace_children}" == false ]] ||
            checks+=("${namespace_scope}" "${namespace_label}" "Microsoft.EventHub/namespaces/authorizationRules/read")
    fi
    if [[ "${needs_entra}" == true ]]; then
        checks+=(
            "/providers/microsoft.aadiam" "Microsoft Entra ID" "microsoft.aadiam/diagnosticSettings/write"
            "${namespace_scope}" "${namespace_label}" "Microsoft.EventHub/namespaces/authorizationRules/listKeys/action")
    fi
    if [[ -z "${foreign_assignment}" ]]; then
        checks+=(
            "${MG_SCOPE}" "tenant root management group" "Microsoft.Insights/diagnosticSettings/read"
            "${MG_SCOPE}" "tenant root management group" "Microsoft.Authorization/roleDefinitions/read"
            "${MG_SCOPE}" "tenant root management group" "Microsoft.Authorization/policyDefinitions/read"
            "${MG_SCOPE}" "tenant root management group" "Microsoft.Authorization/roleDefinitions/write"
            "${MG_SCOPE}" "tenant root management group" "Microsoft.Authorization/policyDefinitions/write"
            "${MG_SCOPE}" "tenant root management group" "Microsoft.Authorization/policyAssignments/write"
            "${MG_SCOPE}" "tenant root management group" "Microsoft.Authorization/roleAssignments/write")
    fi
    [[ "${DRY_RUN}" == true && -n "${foreign_assignment}" ]] ||
        checks+=("${MG_SCOPE}" "tenant root management group" "Microsoft.PolicyInsights/remediations/read")
    [[ "${DRY_RUN}" == true ]] ||
        checks+=("${MG_SCOPE}" "tenant root management group" "Microsoft.PolicyInsights/remediations/write")
    require_permissions "${checks[@]}"
}

main() {
    parse_args "$@"
    validate_args
    derive_names
    preflight_cli
    require_lookup_permissions
    resolve_config_principal
    select_namespace
    EXPORT_RULE_ID="${NAMESPACE_ID}/authorizationRules/${EXPORT_RULE_NAME}"

    local entra_settings foreign_assignment needs_entra uses_export_rule
    entra_settings=$(arm_get_optional "${ARM}/providers/microsoft.aadiam/diagnosticSettings?api-version=2017-04-01" ResourceNotFound)
    [[ -z "${entra_settings}" ]] ||
        printf '%s' "${entra_settings}" | jq -e '(.value | type) == "array"' >/dev/null ||
        die "Azure returned an invalid diagnostic-setting list for Microsoft Entra ID."
    needs_entra=true
    namespace_export_exists "${entra_settings}" AuditLogs && needs_entra=false
    foreign_assignment=$(find_foreign_activity_policy)
    uses_export_rule=false
    [[ "${needs_entra}" == true || -z "${foreign_assignment}" ]] && uses_export_rule=true

    CONFIG_HUB_SUBSCRIPTION_ID="${NAMESPACE_ID#/subscriptions/}"
    CONFIG_HUB_SUBSCRIPTION_ID="${CONFIG_HUB_SUBSCRIPTION_ID%%/*}"
    ensure_insights_provider "${CONFIG_HUB_SUBSCRIPTION_ID}"
    require_setup_permissions "${needs_entra}" "${foreign_assignment}" "${uses_export_rule}"
    [[ "${needs_entra}" == false ]] || require_entra_setting_slot "${entra_settings}"
    if [[ -z "${foreign_assignment}" ]]; then
        require_adoptable_shared_definitions
        adoptable_policy_assignment >/dev/null
    fi
    if [[ "${NAMESPACE_EXISTS}" == true && "${uses_export_rule}" == true ]]; then
        adoptable_export_rule_exists || true
    fi
    [[ "${needs_entra}" == true ]] || log "Adopted an existing Entra ID AuditLogs export to ${EVENT_HUB_NAME}."
    [[ "${DRY_RUN}" == true ]] && log "Dry run: no Azure resources or remediation tasks will be created."

    [[ "${ADOPTED}" == true ]] || ensure_own_namespace
    ensure_event_hub
    ensure_consumer_group
    assign_role "${CONFIG_SP_OBJECT_ID}" "${DATA_RECEIVER_ROLE_ID}" "${NAMESPACE_ID}" \
        "Azure Event Hubs Data Receiver to the Config service principal"

    [[ "${uses_export_rule}" == false ]] || ensure_export_rule
    [[ "${needs_entra}" == false ]] || ensure_entra_export

    if [[ -n "${foreign_assignment}" ]]; then
        ASSIGNMENT_ID="${foreign_assignment}"
        log "Adopted existing Activity Log policy assignment ${ASSIGNMENT_ID}."
    else
        ensure_activity_log_policy
    fi

    if [[ "${DRY_RUN}" == true ]]; then
        if [[ -z "${foreign_assignment}" ]]; then
            collect_subscription_snapshot
            prepare_remediation_plan
            withhold_remediation_without_setting_slot
        fi
        log "Dry run complete."
        return 0
    fi

    log "Azure resources for AWS Config were created successfully."
    collect_subscription_snapshot
    validate_remediation_snapshot
    prepare_remediation_plan
    [[ -n "${foreign_assignment}" ]] || withhold_remediation_without_setting_slot
    submit_remediation_tasks
    print_result
    local failed_count
    failed_count=$(printf '%s' "${FAILED_SUBSCRIPTIONS_JSON}" | jq 'length')
    if [[ "${failed_count}" -gt 0 ]]; then
        warn "Failed to submit remediation for ${failed_count} subscription(s); see remediationTargets[].failedSubscriptions in the JSON result."
        warn "Re-running this script resubmits remediation for every subscription without a task currently in progress, including ones that already succeeded, not just the ones that failed."
    fi
}

main "$@"
