#!/usr/bin/env bash
# Script 2 of 3: deploy the generated Azure telemetry Bicep into the tenant.
#
# This is the STATIC half of the setup/deploy bundle. The DYNAMIC half - the
# per-connection Bicep artifacts (main.bicep and any modules) - is generated
# separately for the connection. Write those files into a setup directory,
# then run this script with the flags below.
#
# Earlier templates require the telemetry service principal object id as a
# parameter. Newer templates resolve it through Microsoft Graph instead.
# Only pass parameters the template declares.
#
# When the connection's hub subscription is already configured, main.bicep
# defaults hubSubscriptionId to it and the deployment must not override it.
# Otherwise main.bicep declares it without a default and
# --hub-subscription-id supplies it. A main.bicep that does not declare
# hubSubscriptionId is never passed one.
#
# --connector-id builds the Azure deployment record name as
# aws-cloudwatch-<connectorId>-<location>, shortened to fit Azure's 64-character
# limit while keeping the whole location. ARM keeps the location of a name's
# first deployment and rejects that name in any other location, so re-running
# this script for the same connection updates the same deployment record
# instead of creating a new one each time. --deployment-name overrides the
# built name directly.
#
# --location is only authoritative on a connector's first-ever run after
# this; see --help for details.
#
# Before deploying, this script checks that the signed-in account has the
# Azure permissions the deployment needs, and reports anything missing
# before changing anything.
#
# After the deployment succeeds, remediation for existing (pre-connection)
# resources is submitted automatically for every entry in the deployment's own
# remediationTargets output (policyAssignmentId, tenantWide, subscriptionIds) -
# one per configured policy (logs, plus VNet/subnet/NIC flow logs when
# selected), no flag needed. A target's tenantWide true means every
# subscription under --tenant-id is discovered and remediated against that
# target's policy assignment, instead of just the ones in subscriptionIds. A
# subscription that fails to start remediation doesn't fail the script; it's
# reported on stderr. A subscription with a remediation already in progress
# for the same policy assignment is skipped, not resubmitted; 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.
#
# Progress is written to stderr. On success, stdout contains one JSON object
# describing the deployment and what remediation did (pretty-printed when
# stdout is a terminal, compact otherwise): deploymentName, tenantId,
# clientId, hubSubscriptionId (null when the template did not need one;
# "unreadable" when it sets a default this script could not parse),
# telemetrySpTenantVerified (null when the template has no such check), and
# remediationTargets - one entry per policy assignment, each with
# policyAssignmentId, tenantWide, the subscriptionIds remediation was
# submitted for, failedSubscriptions (subscriptionId plus error, for any that
# failed to start), and alreadyRunning (subscriptionId plus remediationName,
# for any subscription that already had a remediation in progress for that
# assignment).
#
# Per-connection inputs, supplied as flags:
#   --client-id            telemetry app client id (script 1's appId)
#   --tenant-id            Azure tenant / root management group id
#   --location             deployment metadata location (e.g. eastus)
#   --template-file        path to the generated main.bicep in the setup directory
#   --hub-subscription-id  subscription that hosts the telemetry event hubs;
#                          required only when main.bicep declares it without
#                          a default
#   --connector-id         the connection's connector id; builds the deployment
#                          record name (see above)
#   --deployment-name      overrides the built deployment record name;
#                          required when --connector-id is not given
#
# The template file must already exist before this runs.

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"
ARM="https://management.azure.com"

CLIENT_ID=""
TENANT_ID=""
LOCATION=""
HUB_SUBSCRIPTION_ID=""
TEMPLATE_FILE=""
DEPLOYMENT_NAME=""
CONNECTOR_ID=""

usage() {
    cat >&2 <<EOF
Usage: $0 --client-id <guid> --tenant-id <guid> --location <location> \\
          --template-file <path/to/main.bicep> [--hub-subscription-id <guid>] \\
          (--connector-id <id> | --deployment-name <name> | --deployment-name=<name>)

Deploys the generated Azure telemetry Bicep into the tenant root management
group. The Bicep artifacts must already be written to disk; --template-file
points at the generated main.bicep. --hub-subscription-id is required only
when main.bicep declares hubSubscriptionId without a default.

--connector-id names the connection whose deployment this is; the script
builds the Azure deployment record name from it as
aws-cloudwatch-<connector-id>-<location> (shortened to fit Azure's
64-character limit), so re-running this script for the same connection
updates the same deployment record. --deployment-name overrides that name
directly; it must be 1-64 characters using only letters, numbers,
underscores, parentheses, hyphens, and periods. Use the
--deployment-name=<name> form when the name begins with two hyphens. One of
--connector-id or --deployment-name is required.

--location is only authoritative on a connector's first-ever run. With
--connector-id, this script looks up whether the connector already has a
prior deployment; if found, its location overrides --location instead, so
the deployment stays a stable update-in-place and never drifts across runs.
When that lookup finds nothing, it also checks for an existing policy from
a previous run before giving up. Only when both come back empty is this
treated as a first run, with --location used unchanged.

After the deployment succeeds, remediation for existing resources is
submitted automatically for every entry in the deployment's remediationTargets
output; when an entry's tenantWide is true, every subscription under
--tenant-id is remediated against that entry's policy assignment instead of
just the ones in its subscriptionIds. A subscription with remediation already
in progress for the same policy assignment is skipped, not resubmitted.
EOF
    exit "${1:-1}"
}

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

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

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

EFFECTIVE_HUB_SUBSCRIPTION_ID=""
TELEMETRY_SP_TENANT_VERIFIED_OUTPUT=""
DEPLOYMENT_STATUS_MESSAGE=""
REMEDIATION_RESULTS_JSON='[]'
FAILED_SUBSCRIPTIONS_JSON='[]'
ALREADY_RUNNING_JSON='[]'
REMEDIATION_PLAN_JSON='[]'
ASSIGNMENT_ID=""
SUBSCRIPTION_IDS_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}$ ]]
}

# 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"
}

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
}

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}'."
}

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}"
}

# Discovers every enabled subscription under $TENANT_ID and sets SUBSCRIPTION_IDS_JSON to a
# sorted, deduplicated, lowercased JSON array of their ids. A subscription this sign-in cannot
# see, or that is not Enabled, is left out and reported on stderr rather than failing the script.
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."
}

# Checks $SUBSCRIPTION_IDS_JSON against $ASSIGNMENT_ID for a remediation task already Accepted,
# Evaluating, Running or InProgress, and sets REMEDIATION_PLAN_JSON to one {subscriptionId,
# activeName} entry per subscription (activeName empty when none is active). A subscription
# whose remediation list can't be read is recorded in FAILED_SUBSCRIPTIONS_JSON instead.
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}"
}

# Submits a remediation task for every subscription in REMEDIATION_PLAN_JSON with no active
# one, against $ASSIGNMENT_ID. A subscription with an active name is left running, not
# resubmitted, and counted in ALREADY_RUNNING_JSON. A failed submission goes to
# FAILED_SUBSCRIPTIONS_JSON instead of failing the script.
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."
}

# Builds the Azure deployment record name for a connection: the full location stays at the end
# (ARM pins a name's location on its first deployment), and the connector id is shortened to
# make room. Prints nothing when the result would not fit Azure's naming rules.
azure_deployment_name() {
    local connector_id="$1" location="$2" prefix="aws-cloudwatch-" suffix name max_connector_len
    suffix="-${location}"
    max_connector_len=$((64 - ${#prefix} - ${#suffix}))
    [[ ${max_connector_len} -gt 0 ]] || return 0
    name="${prefix}${connector_id:0:max_connector_len}${suffix}"
    [[ ${#name} -le 64 && "${name}" =~ ^[-A-Za-z0-9_.()]+$ ]] || return 0
    printf '%s' "${name}"
}

azure_resource_groups_deployment_name() {
    local connector_id="$1" prefix="aws-cloudwatch-ingestion-" suffix="-resource-groups" name
    name="${prefix}${connector_id:0:23}${suffix}"
    [[ "${name}" =~ ^[-A-Za-z0-9_.()]+$ ]] || return 0
    printf '%s' "${name}"
}

azure_account_and_region() {
    local file="$1" match value
    match="$(grep -m 1 -oE "resourceGroup\(hubSubscriptionId, '[^']+'\)" "${file}")" || return 0
    value="${match#*\'}"
    value="${value%\'*}"
    [[ "${value}" =~ ^aws-cloudwatch-ingestion-([0-9]{12})-(.+)-[a-z0-9]+$ ]] || return 0
    printf '%s %s' "${BASH_REMATCH[1]}" "${BASH_REMATCH[2]}"
}

print_result() {
    local jq_flags=(-nM)
    [[ -t 1 ]] || jq_flags+=(-c)
    jq "${jq_flags[@]}" \
        --arg deploymentName "${DEPLOYMENT_NAME}" \
        --arg tenantId "${TENANT_ID}" \
        --arg clientId "${CLIENT_ID}" \
        --arg hubSubscriptionId "${EFFECTIVE_HUB_SUBSCRIPTION_ID}" \
        --arg telemetrySpTenantVerified "${TELEMETRY_SP_TENANT_VERIFIED_OUTPUT}" \
        --argjson remediationTargets "${REMEDIATION_RESULTS_JSON}" \
        '{
            deploymentName: $deploymentName,
            tenantId: $tenantId,
            clientId: $clientId,
            hubSubscriptionId: (if $hubSubscriptionId == "" then null else $hubSubscriptionId end),
            telemetrySpTenantVerified: (if $telemetrySpTenantVerified == "" then null else true end),
            remediationTargets: $remediationTargets
        }'
}

while [[ $# -gt 0 ]]; do
    case "$1" in
        --client-id) require_value "$1" "${2:-}"; CLIENT_ID="$2"; shift 2 ;;
        --tenant-id) require_value "$1" "${2:-}"; TENANT_ID="$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 ;;
        --template-file) require_value "$1" "${2:-}"; TEMPLATE_FILE="$2"; shift 2 ;;
        --connector-id) require_value "$1" "${2:-}"; CONNECTOR_ID="$2"; shift 2 ;;
        --deployment-name=*)
            DEPLOYMENT_NAME="${1#--deployment-name=}"
            [[ -n "${DEPLOYMENT_NAME}" ]] || {
                echo "Error: --deployment-name requires a value." >&2
                usage
            }
            shift
            ;;
        --deployment-name) require_value "$1" "${2:-}"; DEPLOYMENT_NAME="$2"; shift 2 ;;
        -h|--help) usage 0 ;;
        *) echo "Error: unknown argument $1" >&2; usage ;;
    esac
done

is_guid "${CLIENT_ID}" || die "The --client-id flag must be a GUID."
is_guid "${TENANT_ID}" || die "The --tenant-id flag must be a GUID."
TENANT_ID="$(lower "${TENANT_ID}")"
MG_SCOPE="/providers/Microsoft.Management/managementGroups/${TENANT_ID}"
[[ -z "${HUB_SUBSCRIPTION_ID}" ]] || is_guid "${HUB_SUBSCRIPTION_ID}" ||
    die "The --hub-subscription-id flag must be a GUID."
[[ -n "${LOCATION}" ]] || die "The --location flag is required."
LOCATION="$(lower "${LOCATION}")"
[[ "${LOCATION}" =~ ^[a-z0-9]+$ ]] || die "Invalid --location '${LOCATION}'."
[[ -n "${TEMPLATE_FILE}" ]] || die "The --template-file flag is required."
[[ -f "${TEMPLATE_FILE}" ]] || die "Template file not found: ${TEMPLATE_FILE}"
[[ -r "${TEMPLATE_FILE}" ]] || die "Template file is not readable: ${TEMPLATE_FILE}"
if [[ -n "${DEPLOYMENT_NAME}" ]]; then
    [[ ${#DEPLOYMENT_NAME} -le 64 && "${DEPLOYMENT_NAME}" =~ ^[-A-Za-z0-9_.()]+$ ]] ||
        die "The --deployment-name flag must be 1-64 characters using only letters, numbers, underscores, parentheses, hyphens, and periods."
elif [[ -z "${CONNECTOR_ID}" ]]; then
    die "--connector-id is required (or --deployment-name)."
fi
if grep -qE '^[[:space:]]*param[[:space:]]+resourceGroupsDeploymentName[[:space:]]' "${TEMPLATE_FILE}" && [[ -z "${CONNECTOR_ID}" ]]; then
    die "${TEMPLATE_FILE} requires resourceGroupsDeploymentName, which this script only builds from --connector-id; --deployment-name alone cannot supply it."
fi

# A default means the service rendered the manifest's subscription into Bicep.
DEFAULTED_HUB_PARAM="$(grep -m 1 -E '^[[:space:]]*param[[:space:]]+hubSubscriptionId[[:space:]]+string[[:space:]]*=' "${TEMPLATE_FILE}" || true)"
DECLARES_HUB_PARAM=false
if grep -qE '^[[:space:]]*param[[:space:]]+hubSubscriptionId[[:space:]]' "${TEMPLATE_FILE}"; then
    DECLARES_HUB_PARAM=true
fi
PASS_HUB_SUBSCRIPTION_ID=false
if [[ -n "${DEFAULTED_HUB_PARAM}" ]]; then
    TEMPLATE_HUB_SUBSCRIPTION_ID=""
    DEFAULT_VALUE_PATTERN="=[[:space:]]*'([^']*)'"
    if [[ "${DEFAULTED_HUB_PARAM}" =~ ${DEFAULT_VALUE_PATTERN} ]]; then
        TEMPLATE_HUB_SUBSCRIPTION_ID="${BASH_REMATCH[1]}"
    fi
    if [[ -n "${HUB_SUBSCRIPTION_ID}" && -z "${TEMPLATE_HUB_SUBSCRIPTION_ID}" ]]; then
        warn "Ignoring --hub-subscription-id ${HUB_SUBSCRIPTION_ID}; ${TEMPLATE_FILE} sets the infrastructure subscription with a default this script can't read, and that default applies."
    elif [[ -n "${HUB_SUBSCRIPTION_ID}" &&
        "$(lower "${HUB_SUBSCRIPTION_ID}")" != "$(lower "${TEMPLATE_HUB_SUBSCRIPTION_ID}")" ]]; then
        die "The --hub-subscription-id flag's value, ${HUB_SUBSCRIPTION_ID}, differs from the infrastructure subscription ${TEMPLATE_HUB_SUBSCRIPTION_ID} that ${TEMPLATE_FILE} sets from the connection's settings. You can drop the flag, or change the connection's infrastructure subscription and download the setup again."
    fi
    log "Using the infrastructure subscription set in ${TEMPLATE_FILE}${TEMPLATE_HUB_SUBSCRIPTION_ID:+ (${TEMPLATE_HUB_SUBSCRIPTION_ID})}."
    if [[ -n "${TEMPLATE_HUB_SUBSCRIPTION_ID}" ]]; then
        EFFECTIVE_HUB_SUBSCRIPTION_ID="${TEMPLATE_HUB_SUBSCRIPTION_ID}"
    else
        EFFECTIVE_HUB_SUBSCRIPTION_ID="unreadable"
    fi
elif [[ "${DECLARES_HUB_PARAM}" == true ]]; then
    [[ -n "${HUB_SUBSCRIPTION_ID}" ]] ||
        die "The --hub-subscription-id flag is required because ${TEMPLATE_FILE} declares hubSubscriptionId without a default."
    PASS_HUB_SUBSCRIPTION_ID=true
    EFFECTIVE_HUB_SUBSCRIPTION_ID="${HUB_SUBSCRIPTION_ID}"
elif [[ -n "${HUB_SUBSCRIPTION_ID}" ]]; then
    warn "Ignoring --hub-subscription-id ${HUB_SUBSCRIPTION_ID}; ${TEMPLATE_FILE} does not declare hubSubscriptionId."
fi

preflight_cli

az bicep version >/dev/null 2>&1 ||
    die "The az bicep extension is required. Run 'az bicep install' and re-run this script."

COMPILED_TEMPLATE="$(az bicep build --file "${TEMPLATE_FILE}" --stdout 2>/dev/null)" ||
    die "Could not compile ${TEMPLATE_FILE}. Run 'az bicep build --file ${TEMPLATE_FILE}' to see why."
OTHER_SUBSCRIPTION_WRITES="$(printf '%s' "${COMPILED_TEMPLATE}" | jq -r \
    --arg hub "$(lower "${EFFECTIVE_HUB_SUBSCRIPTION_ID}")" '
    def literal: type == "string" and (startswith("[") | not);
    [.resources[]?
        | select(.type == "Microsoft.Resources/deployments"
            and (.subscriptionId | literal) and (.resourceGroup | literal)
            and (.subscriptionId | ascii_downcase) != $hub)
        | "/subscriptions/\(.subscriptionId)/resourceGroups/\(.resourceGroup)" as $scope
        | "resource group \(.resourceGroup)" as $where
        | ("Microsoft.Resources/deployments/write",
            (.properties.template.resources[]? | select(.existing != true) | "\(.type)/write"))
        | [$scope, $where, .]]
    | unique[] | @tsv')" ||
    die "Could not read the nested deployments of ${TEMPLATE_FILE}."

REQUIRED_PERMISSIONS=(
    "${MG_SCOPE}" "tenant root management group" "Microsoft.Resources/deployments/validate/action"
    "${MG_SCOPE}" "tenant root management group" "Microsoft.Resources/deployments/write"
    "${MG_SCOPE}" "tenant root management group" "Microsoft.Resources/deployments/read"
    "${MG_SCOPE}" "tenant root management group" "Microsoft.Authorization/policyAssignments/write"
    "${MG_SCOPE}" "tenant root management group" "Microsoft.Authorization/roleAssignments/write"
)
if grep -qE '^[[:space:]]*output[[:space:]]+remediationTargets[[:space:]]' "${TEMPLATE_FILE}"; then
    REQUIRED_PERMISSIONS+=(
        "${MG_SCOPE}" "tenant root management group" "Microsoft.PolicyInsights/remediations/read"
        "${MG_SCOPE}" "tenant root management group" "Microsoft.PolicyInsights/remediations/write"
        "${MG_SCOPE}" "tenant root management group" "Microsoft.Resources/subscriptions/read")
fi
if grep -qE '^[[:space:]]*param[[:space:]]+resourceGroupsDeploymentName[[:space:]]' "${TEMPLATE_FILE}"; then
    REQUIRED_PERMISSIONS+=(
        "${MG_SCOPE}" "tenant root management group" "Microsoft.Authorization/policyDefinitions/read"
        "${MG_SCOPE}" "tenant root management group" "Microsoft.Authorization/policyAssignments/read")
fi
if [[ -n "${OTHER_SUBSCRIPTION_WRITES}" ]]; then
    while IFS=$'\t' read -r WRITE_SCOPE WRITE_LABEL WRITE_ACTION; do
        REQUIRED_PERMISSIONS+=("${WRITE_SCOPE}" "${WRITE_LABEL}" "${WRITE_ACTION}")
    done <<<"${OTHER_SUBSCRIPTION_WRITES}"
fi
require_permissions "${REQUIRED_PERMISSIONS[@]}"

RESOURCE_GROUPS_DEPLOYMENT_NAME=""
if [[ -n "${CONNECTOR_ID}" ]]; then
    RESOURCE_GROUPS_DEPLOYMENT_NAME="$(azure_resource_groups_deployment_name "${CONNECTOR_ID}")"
fi

if [[ -n "${RESOURCE_GROUPS_DEPLOYMENT_NAME}" ]] && is_guid "${EFFECTIVE_HUB_SUBSCRIPTION_ID}" &&
    grep -qE '^[[:space:]]*param[[:space:]]+resourceGroupsDeploymentName[[:space:]]' "${TEMPLATE_FILE}"; then
    RESOURCE_GROUPS_FOUND=false
    error_file=$(mktemp "${TMPDIR:-/tmp}/cloudwatch-azure-cli-error.XXXXXX") ||
        die "Failed to create a temporary file to check for an existing resource-groups deployment ${RESOURCE_GROUPS_DEPLOYMENT_NAME}."
    if EXISTING_RESOURCE_GROUPS_LOCATION="$(az deployment sub show \
        --name "${RESOURCE_GROUPS_DEPLOYMENT_NAME}" \
        --subscription "${EFFECTIVE_HUB_SUBSCRIPTION_ID}" \
        --query location --output tsv --only-show-errors 2>"${error_file}")"; then
        rm -f -- "${error_file}"
        [[ -n "${EXISTING_RESOURCE_GROUPS_LOCATION}" ]] && RESOURCE_GROUPS_FOUND=true
    else
        error_output=$(cat -- "${error_file}")
        rm -f -- "${error_file}"
        [[ "${error_output}" == *DeploymentNotFound* ]] ||
            die "Could not check for an existing resource-groups deployment ${RESOURCE_GROUPS_DEPLOYMENT_NAME}: ${error_output}"
    fi
    if [[ "${RESOURCE_GROUPS_FOUND}" == true ]]; then
        EXISTING_RESOURCE_GROUPS_LOCATION="$(lower "${EXISTING_RESOURCE_GROUPS_LOCATION}")"
        if [[ "${EXISTING_RESOURCE_GROUPS_LOCATION}" != "${LOCATION}" ]]; then
            log "Found an existing resource-groups deployment (${RESOURCE_GROUPS_DEPLOYMENT_NAME}) for connector ${CONNECTOR_ID} at location ${EXISTING_RESOURCE_GROUPS_LOCATION}; using that location instead of --location ${LOCATION} so this run updates it in place."
            LOCATION="${EXISTING_RESOURCE_GROUPS_LOCATION}"
        fi
    else
        log "Could not find an existing resource-groups deployment for connector ${CONNECTOR_ID}; checking for an existing diag logs policy next."
        AWS_ACCOUNT_AND_REGION="$(azure_account_and_region "${TEMPLATE_FILE}")"
        POLICY_DEFINITION_ID=""
        if [[ -n "${AWS_ACCOUNT_AND_REGION}" ]]; then
            read -r AWS_ACCOUNT AWS_REGION <<<"${AWS_ACCOUNT_AND_REGION}"
            error_file=$(mktemp "${TMPDIR:-/tmp}/cloudwatch-azure-cli-error.XXXXXX") ||
                die "Failed to create a temporary file to check for an existing diaglogs policy definition for connector ${CONNECTOR_ID}."
            if POLICY_DEFINITION_ID="$(az policy definition show \
                --name "aws-cloudwatch-ingestion-diaglogs-${AWS_ACCOUNT}-${AWS_REGION}" \
                --management-group "${TENANT_ID}" \
                --query id --output tsv --only-show-errors 2>"${error_file}")"; then
                rm -f -- "${error_file}"
            else
                error_output=$(cat -- "${error_file}")
                rm -f -- "${error_file}"
                [[ "${error_output}" == *PolicyDefinitionNotFound* ]] ||
                    die "Could not check for an existing diaglogs policy definition for connector ${CONNECTOR_ID}: ${error_output}"
                POLICY_DEFINITION_ID=""
            fi
        fi
        POLICY_FOUND=false
        if [[ -n "${POLICY_DEFINITION_ID}" ]]; then
            error_file=$(mktemp "${TMPDIR:-/tmp}/cloudwatch-azure-cli-error.XXXXXX") ||
                die "Failed to create a temporary file to check for an existing policy assignment for connector ${CONNECTOR_ID}."
            if POLICY_ASSIGNMENTS_JSON="$(az policy assignment list \
                --scope "${MG_SCOPE}" \
                --output json --only-show-errors 2>"${error_file}")"; then
                rm -f -- "${error_file}"
            else
                error_output=$(cat -- "${error_file}")
                rm -f -- "${error_file}"
                die "Could not check for an existing policy assignment for connector ${CONNECTOR_ID}: ${error_output}"
            fi
            EXISTING_POLICY_LOCATION="$(printf '%s' "${POLICY_ASSIGNMENTS_JSON}" | jq -r --arg id "${POLICY_DEFINITION_ID}" \
                '([.[] | select((.policyDefinitionId // "" | ascii_downcase) == ($id | ascii_downcase))][0].location) // ""')"
            [[ -n "${EXISTING_POLICY_LOCATION}" && "${EXISTING_POLICY_LOCATION}" != "null" ]] && POLICY_FOUND=true
        fi
        if [[ "${POLICY_FOUND}" == true ]]; then
            EXISTING_POLICY_LOCATION="$(lower "${EXISTING_POLICY_LOCATION}")"
            if [[ "${EXISTING_POLICY_LOCATION}" != "${LOCATION}" ]]; then
                log "Found an existing policy assignment for connector ${CONNECTOR_ID} at location ${EXISTING_POLICY_LOCATION}; using that location instead of --location ${LOCATION} so this run updates it in place."
                LOCATION="${EXISTING_POLICY_LOCATION}"
            fi
        else
            warn "Could not find an existing resource-groups deployment (${RESOURCE_GROUPS_DEPLOYMENT_NAME}) for connector ${CONNECTOR_ID}; treating this run as its first and keeping --location ${LOCATION}."
        fi
    fi
fi

if [[ -z "${DEPLOYMENT_NAME}" ]]; then
    DEPLOYMENT_NAME="$(azure_deployment_name "${CONNECTOR_ID}" "${LOCATION}")"
    [[ -n "${DEPLOYMENT_NAME}" ]] ||
        die "Could not build a deployment name from --connector-id ${CONNECTOR_ID} and --location ${LOCATION}."
fi

if [[ "${PASS_HUB_SUBSCRIPTION_ID}" == true ]]; then
    ensure_insights_provider "${HUB_SUBSCRIPTION_ID}"
elif [[ -n "${TEMPLATE_HUB_SUBSCRIPTION_ID:-}" ]]; then
    ensure_insights_provider "${TEMPLATE_HUB_SUBSCRIPTION_ID}"
fi

DEPLOY_ARGS=(
    "--name=${DEPLOYMENT_NAME}"
    --management-group-id "${TENANT_ID}"
    --location "${LOCATION}"
    --template-file "${TEMPLATE_FILE}"
)
PASS_TELEMETRY_SP_OBJECT_ID=false
if grep -qE '^[[:space:]]*param[[:space:]]+telemetrySpObjectId[[:space:]]' "${TEMPLATE_FILE}"; then
    # One lookup for both fields, so the tenant check below is free. The
    # projection is double-bracketed because the CLI renders a bare
    # multiselect list as one value per LINE; wrapping it in a list makes it
    # one tab-separated row, which is what the read below expects.
    TELEMETRY_SP="$(az ad sp show --id "${CLIENT_ID}" --query '[[id,appOwnerOrganizationId]]' --output tsv)" ||
        die "Could not look up the service principal for client id ${CLIENT_ID} in tenant ${TENANT_ID} (see the Azure CLI error above). If script 1 has not run or just finished, run it or wait a minute and retry."
    IFS=$'\t' read -r TELEMETRY_SP_OBJECT_ID TELEMETRY_SP_OWNER_TENANT <<<"${TELEMETRY_SP}"
    is_guid "${TELEMETRY_SP_OBJECT_ID}" ||
        die "Could not resolve service principal object id for client id ${CLIENT_ID}. An application registration on its own is not enough: it needs a service principal in tenant ${TENANT_ID}."
    # Checked before deploying. The template's own gate let a mismatch create
    # every resource and then grant nothing, which reads as success.
    [[ "$(lower "${TELEMETRY_SP_OWNER_TENANT}")" == "$(lower "${TENANT_ID}")" ]] ||
        die "The telemetry application ${CLIENT_ID} is owned by Azure tenant ${TELEMETRY_SP_OWNER_TENANT:-unknown}, not --tenant-id ${TENANT_ID}. Nothing was deployed. Check that the connection uses the application that the Microsoft Entra setup created in this tenant, then run this command again."
    DEPLOY_ARGS+=(--parameters "telemetrySpObjectId=${TELEMETRY_SP_OBJECT_ID}")
    PASS_TELEMETRY_SP_OBJECT_ID=true
fi
if [[ "${PASS_HUB_SUBSCRIPTION_ID}" == true ]]; then
    if [[ "${PASS_TELEMETRY_SP_OBJECT_ID}" == false ]]; then
        DEPLOY_ARGS+=(--parameters)
    fi
    DEPLOY_ARGS+=("hubSubscriptionId=${HUB_SUBSCRIPTION_ID}")
fi
if grep -qE '^[[:space:]]*param[[:space:]]+resourceGroupsDeploymentName[[:space:]]' "${TEMPLATE_FILE}"; then
    [[ -n "${RESOURCE_GROUPS_DEPLOYMENT_NAME}" ]] ||
        die "Could not build resourceGroupsDeploymentName from --connector-id ${CONNECTOR_ID}; ${TEMPLATE_FILE} requires it."
    if [[ "${PASS_TELEMETRY_SP_OBJECT_ID}" == false && "${PASS_HUB_SUBSCRIPTION_ID}" == false ]]; then
        DEPLOY_ARGS+=(--parameters)
    fi
    DEPLOY_ARGS+=("resourceGroupsDeploymentName=${RESOURCE_GROUPS_DEPLOYMENT_NAME}")
fi

if ! VALIDATION_ERROR="$(az deployment mg validate "${DEPLOY_ARGS[@]}" --output none 2>&1)"; then
    PERMISSION_DENIED_PATTERN="does not have permission to perform action '([^']+)' at scope '([^']+)'"
    VALIDATION_MISSING=()
    while IFS=$'\t' read -r MISSING_ACTION MISSING_PLACE; do
        VALIDATION_MISSING+=("${MISSING_ACTION}" "${MISSING_PLACE}")
    done < <(printf '%s' "${VALIDATION_ERROR}" | jq -Rrs --arg tenant "${TENANT_ID}" \
        --arg pattern "${PERMISSION_DENIED_PATTERN}" '
        def plural($count; $noun): if $count == 1 then $noun else "\($noun)s" end;
        def place:
            . as $scope | split("/") as $parts
            | if test("^/subscriptions/[^/]+/resourceGroups/[^/]+/."; "i") then
                {kind: "resource", subscription: $parts[2], resourceGroup: $parts[4]}
            elif test("^/subscriptions/[^/]+/resourceGroups/[^/]+$"; "i") then
                {kind: "resourceGroup", subscription: $parts[2], resourceGroup: $parts[4]}
            elif test("^/subscriptions/[^/]+$"; "i") then
                {kind: "subscription", subscription: $parts[2]}
            elif ascii_downcase == "/providers/microsoft.management/managementgroups/\($tenant)" then
                {kind: "label", text: "tenant root management group (\($scope))"}
            elif test("^/providers/Microsoft.Management/managementGroups/[^/]+$"; "i") then
                {kind: "label", text: "management group \($parts[4]) (\($scope))"}
            else
                {kind: "label", text: $scope}
            end;
        def describe:
            (map(.resourceGroup) | unique) as $groups
            | if .[0].kind == "resource" then
                "\(length) \(plural(length; "resource")) in \(plural($groups | length; "resource group")) \($groups | join(", ")) of subscription \(.[0].subscription)"
            elif .[0].kind == "resourceGroup" then
                "\(plural($groups | length; "resource group")) \($groups | join(", ")) of subscription \(.[0].subscription)"
            elif .[0].kind == "subscription" then
                "subscription \(.[0].subscription)"
            else
                map(.text) | join("; ")
            end;
        [scan($pattern)] | unique | group_by(.[0])[]
        | [.[0][0], ([.[][1] | place] | group_by([.kind, .subscription]) | map(describe) | join("; "))]
        | @tsv')
    VALIDATION_SUMMARY="$(printf '%s' "${VALIDATION_ERROR}" | jq -Rsc --arg pattern "${PERMISSION_DENIED_PATTERN}" \
        --arg multiple "Deployment failed with multiple errors: '" '
        def sentences: gsub("(?<end>\\.\\x27?)\\s+"; "\(.end)\n") | split("\n") | map(select(length > 0));
        . as $raw
        | ([match("\\{.*\\}").string | fromjson? | objects] | first) as $error
        | if ($error.message | type) == "string" then
            $error.message as $message
            | (if ($error.code | type) == "string" then "\($error.code): " else "" end) as $code
            | if ($message | startswith($multiple)) then
                ($message | ltrimstr($multiple) | rtrimstr("\u0027")
                    | [splits("\\.:(?=\\S)")] | map(if endswith(".") then . else "\(.)." end)) as $entries
                | {entries: $entries, lines: (["\($code)Deployment failed with multiple errors:"] + $entries)}
            else
                {entries: [$message], lines: ($message | sentences | .[0] |= "\($code)\(.)")}
            end
        else
            {entries: null, lines: ($raw | sentences)}
        end
        | ([$raw | scan($pattern)] | length) as $matches
        | {lines, total: (.entries // [] | length),
            unsummarised: (if .entries == null then null
                else ([.entries[] | select(test($pattern) | not)] | length) as $other
                    | if (.entries | length) - $other == $matches then $other else null end
                end)}')"
    VALIDATION_INLINE="  Azure's validation error:"$'\n'"$(printf '%s' "${VALIDATION_SUMMARY}" |
        jq -r '.lines | map("    \(.)") | join("\n")')"
    VALIDATION_REPORT=""
    if [[ ${#VALIDATION_MISSING[@]} -eq 0 ]]; then
        VALIDATION_DETAIL="${VALIDATION_INLINE}"
    else
        VALIDATION_REPORT="$(missing_permissions_report "${VALIDATION_MISSING[@]}")"
        VALIDATION_UNSUMMARISED="$(printf '%s' "${VALIDATION_SUMMARY}" | jq -r '.unsummarised // "unknown"')"
        VALIDATION_TOTAL="$(printf '%s' "${VALIDATION_SUMMARY}" | jq -r '.total')"
        VALIDATION_LOG="./cloudwatch-azure-setup-$(jq -rn 'now | strftime("%Y%m%dT%H%M")').log"
        if [[ -L "${VALIDATION_LOG}" ]] || ! (umask 077 && printf '%s\n' \
            "Azure's validation error for deployment '${DEPLOYMENT_NAME}':" "${VALIDATION_ERROR}" \
            >>"${VALIDATION_LOG}") 2>/dev/null; then
            VALIDATION_LOG=""
        fi
        if [[ -n "${VALIDATION_LOG}" ]]; then
            VALIDATION_DETAIL="  Azure's full validation error is in ${VALIDATION_LOG}."
            case "${VALIDATION_UNSUMMARISED}" in
                0) ;;
                unknown) VALIDATION_DETAIL+=$'\n'"  Azure's error may list more than the lines above." ;;
                *) VALIDATION_DETAIL+=$'\n'"  Not summarised above: ${VALIDATION_UNSUMMARISED} of the ${VALIDATION_TOTAL} entries in Azure's error, in that log." ;;
            esac
        else
            case "${VALIDATION_UNSUMMARISED}" in
                0) VALIDATION_DETAIL="" ;;
                unknown) VALIDATION_DETAIL="  Azure's error below may list more than the lines above."$'\n' ;;
                *) VALIDATION_DETAIL="  Not summarised above: ${VALIDATION_UNSUMMARISED} of the ${VALIDATION_TOTAL} entries in Azure's error below."$'\n' ;;
            esac
            VALIDATION_DETAIL+="${VALIDATION_INLINE}"
        fi
    fi
    die "Azure's validation of deployment '${DEPLOYMENT_NAME}' failed, so it was not started. Nothing has been changed.${VALIDATION_REPORT}"$'\n'"${VALIDATION_DETAIL}"
fi

if grep -qE '^[[:space:]]*output[[:space:]]+telemetrySpTenantVerified[[:space:]]' "${TEMPLATE_FILE}"; then
    TENANT_CHECK_QUERY='properties.outputs.telemetrySpTenantVerified.value || properties.outputs.telemetrysptenantverified.value'
    TELEMETRY_SP_TENANT_VERIFIED="$(az deployment mg create "${DEPLOY_ARGS[@]}" --query "${TENANT_CHECK_QUERY}" --output tsv)" ||
        die "The Azure deployment failed. Check the Azure CLI error above."
    case "${TELEMETRY_SP_TENANT_VERIFIED}" in
        [Tt][Rr][Uu][Ee]) ;;
        *) die "The deployment finished, but it granted no roles to the telemetry application because its service principal isn't owned by Azure tenant ${TENANT_ID}. Check that the connection uses the application that the Microsoft Entra setup created in this tenant, then run this command again." ;;
    esac
    TELEMETRY_SP_TENANT_VERIFIED_OUTPUT="true"
    DEPLOYMENT_STATUS_MESSAGE="Bicep deployment '${DEPLOYMENT_NAME}' finished; the telemetry application's role grants were verified."
else
    az deployment mg create "${DEPLOY_ARGS[@]}" --output none ||
        die "The Azure deployment failed. Check the Azure CLI error above."
    DEPLOYMENT_STATUS_MESSAGE="Bicep deployment '${DEPLOYMENT_NAME}' finished."
fi

# One read of the deployment's outputs, parsed locally with jq, instead of a separate
# az deployment mg show per remediationTargets field.
REMEDIATION_TARGETS_JSON="$(az deployment mg show \
    "--name=${DEPLOYMENT_NAME}" \
    --management-group-id "${TENANT_ID}" \
    --query 'properties.outputs.remediationTargets.value' \
    --output json)" ||
    die "Failed to read remediationTargets from the deployment (see the Azure CLI error above)."
[[ "${REMEDIATION_TARGETS_JSON}" != "null" ]] || REMEDIATION_TARGETS_JSON='[]'
printf '%s' "${REMEDIATION_TARGETS_JSON}" | jq -e 'type == "array"' >/dev/null ||
    die "The deployment's remediationTargets output is not an array."

REMEDIATION_TARGET_COUNT="$(printf '%s' "${REMEDIATION_TARGETS_JSON}" | jq 'length')"

[[ "${REMEDIATION_TARGET_COUNT}" -gt 0 ]] ||
    log "The deployment has no remediationTargets output; skipping remediation."

TENANT_SUBSCRIPTION_IDS_JSON=""
TENANT_SUBSCRIPTIONS_DISCOVERED=false

for ((TARGET_INDEX = 0; TARGET_INDEX < REMEDIATION_TARGET_COUNT; TARGET_INDEX++)); do
    TARGET_JSON="$(printf '%s' "${REMEDIATION_TARGETS_JSON}" | jq -c ".[${TARGET_INDEX}]")"

    POLICY_ASSIGNMENT_ID="$(printf '%s' "${TARGET_JSON}" | jq -r '.policyAssignmentId // empty')"
    [[ -n "${POLICY_ASSIGNMENT_ID}" ]] ||
        die "Target remediationTargets[${TARGET_INDEX}].policyAssignmentId is missing."

    TENANT_WIDE="$(printf '%s' "${TARGET_JSON}" | jq -r '.tenantWide')"
    TENANT_WIDE="$(lower "${TENANT_WIDE}")"
    [[ "${TENANT_WIDE}" == "true" || "${TENANT_WIDE}" == "false" ]] ||
        die "Target remediationTargets[${TARGET_INDEX}].tenantWide is '${TENANT_WIDE}', not a boolean."

    if [[ "${TENANT_WIDE}" == "true" ]]; then
        if [[ "${TENANT_SUBSCRIPTIONS_DISCOVERED}" == false ]]; then
            TENANT_SUBSCRIPTIONS_DISCOVERED=true
            collect_subscription_snapshot
            TENANT_SUBSCRIPTION_IDS_JSON="${SUBSCRIPTION_IDS_JSON}"
        fi
        SUBSCRIPTION_IDS_JSON="${TENANT_SUBSCRIPTION_IDS_JSON}"
        [[ "$(printf '%s' "${SUBSCRIPTION_IDS_JSON}" | jq 'length')" -gt 0 ]] ||
            warn "No enabled subscriptions to remediate under tenant ${TENANT_ID} for policy assignment ${POLICY_ASSIGNMENT_ID}; this target still appears in the result with an empty subscriptionIds list."
    else
        SUBSCRIPTION_IDS_JSON="$(printf '%s' "${TARGET_JSON}" | jq -c '[(.subscriptionIds // [])[] | ascii_downcase]')"
        [[ "$(printf '%s' "${SUBSCRIPTION_IDS_JSON}" | jq 'length')" -gt 0 ]] ||
            die "Target remediationTargets[${TARGET_INDEX}].tenantWide is false but subscriptionIds is empty."
        INVALID_SUBSCRIPTION_ID="$(printf '%s' "${SUBSCRIPTION_IDS_JSON}" | jq -r \
            '.[] | select(test("^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$") | not)' | head -n 1)"
        [[ -z "${INVALID_SUBSCRIPTION_ID}" ]] ||
            die "Target remediationTargets[${TARGET_INDEX}].subscriptionIds contains '${INVALID_SUBSCRIPTION_ID}', which is not a GUID."
    fi

    FAILED_SUBSCRIPTIONS_JSON='[]'
    ALREADY_RUNNING_JSON='[]'
    SUBSCRIPTION_COUNT="$(printf '%s' "${SUBSCRIPTION_IDS_JSON}" | jq 'length')"
    if [[ "${SUBSCRIPTION_COUNT}" -gt 0 ]]; then
        log "Checking remediation status for ${SUBSCRIPTION_COUNT} subscription(s) against policy assignment ${POLICY_ASSIGNMENT_ID}."
        ASSIGNMENT_ID="${POLICY_ASSIGNMENT_ID}"
        # Suppressed here because this target is one of possibly several; the aggregate summary
        # after the loop below reports the total across all of them instead.
        SUPPRESS_REMEDIATION_SUMMARY=true
        prepare_remediation_plan
        submit_remediation_tasks
    fi

    REMEDIATION_RESULTS_JSON="$(printf '%s' "${REMEDIATION_RESULTS_JSON}" | jq -c \
        --arg policyAssignmentId "${POLICY_ASSIGNMENT_ID}" \
        --argjson tenantWide "${TENANT_WIDE}" \
        --argjson subscriptionIds "${SUBSCRIPTION_IDS_JSON}" \
        --argjson failedSubscriptions "${FAILED_SUBSCRIPTIONS_JSON}" \
        --argjson alreadyRunning "${ALREADY_RUNNING_JSON}" \
        '. + [{policyAssignmentId:$policyAssignmentId,tenantWide:$tenantWide,subscriptionIds:$subscriptionIds,failedSubscriptions:$failedSubscriptions,alreadyRunning:$alreadyRunning}]')"
done

STARTED_COUNT="$(printf '%s' "${REMEDIATION_RESULTS_JSON}" | jq '[.[] | (.subscriptionIds | length) - (.failedSubscriptions | length) - (.alreadyRunning | length)] | add // 0')"
ALREADY_RUNNING_COUNT="$(printf '%s' "${REMEDIATION_RESULTS_JSON}" | jq '[.[].alreadyRunning | length] | add // 0')"
log "Started ${STARTED_COUNT} remediation tasks successfully."
[[ "${ALREADY_RUNNING_COUNT}" -eq 0 ]] || log "Kept ${ALREADY_RUNNING_COUNT} existing remediation tasks running."
if [[ "$((STARTED_COUNT + ALREADY_RUNNING_COUNT))" -gt 0 ]]; then
    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."
fi
log "${DEPLOYMENT_STATUS_MESSAGE}"

print_result

FAILED_PAIR_COUNT="$(printf '%s' "${REMEDIATION_RESULTS_JSON}" | jq '[.[].failedSubscriptions[]] | length')"
if [[ "${FAILED_PAIR_COUNT}" -gt 0 ]]; then
    FAILED_SUBSCRIPTION_COUNT="$(printf '%s' "${REMEDIATION_RESULTS_JSON}" | jq '[.[].failedSubscriptions[].subscriptionId] | unique | length')"
    warn "Failed to submit remediation for ${FAILED_PAIR_COUNT} subscription/policy-assignment pair(s) across ${FAILED_SUBSCRIPTION_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
