#!/usr/bin/env bash
# Creates or updates the IAM role that lets this account's Azure-vended
# telemetry pipeline write logs, metrics, and traces here. Safe to re-run;
# never removes a managed log-group destination or unrelated trust statement.
#
# Progress goes to stderr. On success, stdout is one JSON object:
#   {status, contractVersion, region, writerRole: {arn, trust, policy},
#    policyName, logGroupArn}
# On any other failure (exit 1): {status: "failed", contractVersion, error, fix?}
# Exit code 2 (invalid input) prints no stdout; the error goes to stderr only.

set -Eeuo pipefail

export AWS_PAGER=""
export LC_ALL=C

trap 'exit 130' INT TERM HUP

SCRIPT_CONTRACT_VERSION="1"

LOG_GROUP_NAME_CHARSET='A-Za-z0-9._/#-'
LOG_GROUP_NAME_MAX_LENGTH=512
LOG_GROUP_RESERVED_PREFIX="aws/"
SERVICE_PRINCIPAL="telemetry-pipelines.observabilityadmin.amazonaws.com"

WRITER_ROLE_ARN=""
AWS_REGION=""
PIPELINE_NAME=""
LOG_GROUP_NAME=""
DRY_RUN=false

PARTITION=""
ACCOUNT_ID=""
ROLE_PATH=""
ROLE_NAME=""
EXPECTED_ROLE_ARN=""

TRUST_SID=""
EXPECTED_TRUST_STATEMENT=""
EXPECTED_POLICY=""
LOG_GROUP_ARN=""
POLICY_NAME=""

ROLE_EXISTS=false
TRUST_STATUS=""
POLICY_STATUS=""
POLICY_ADDS_LOG_GROUP=false
TRUST_RESULT="existing"
POLICY_RESULT="existing"
EXISTING_TRUST_DOC=""
EXISTING_POLICY=""

LAST_ERROR_MSG=""
LAST_ERROR_FIX=""

usage() {
    cat >&2 <<EOF
Usage: $0 --writer-role-arn <arn> --aws-region <region> --pipeline-name <name> \\
          --log-group-name <name> [--dry-run]

Creates or updates the IAM role at --writer-role-arn so the Azure
vended-telemetry pipeline --pipeline-name can write logs to
--log-group-name, metrics, and traces into this AWS account. Adds the requested
log group to the managed policy; never removes a previously managed log-group
destination or an unrelated trust statement.

Required:
  --writer-role-arn <arn>   Full ARN of the writer role, e.g.
                             arn:aws:iam::123456789012:role/CloudWatchAzureWriter
  --aws-region <region>     AWS Region the pipeline writes to, such as us-east-1
  --pipeline-name <name>    Telemetry pipeline name; names the inline policy
  --log-group-name <name>   Log group the pipeline writes to (not aws/*)

Options:
  --dry-run                 Validate inputs and print the plan; make no change
  -h, --help                Show this help

Without --dry-run, prints the plan and asks to continue before changing
anything. Run in a terminal, Enter or y/yes continues and anything else
aborts; run without a terminal on stdin, it proceeds automatically.

On success, stdout is one JSON object: {status, contractVersion,
region, writerRole: {arn, trust, policy}, policyName, logGroupArn}.
writerRole.trust and writerRole.policy are each created, updated, or existing,
reported independently. On any other failure, stdout is {status: "failed",
contractVersion, error, fix?}. Progress goes to stderr. Exit code 2 (a missing
or invalid flag) prints no stdout; exit code 1 is any other failure.
EOF
    exit "${1:-2}"
}

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

print_failure_json() {
    if ! command -v jq >/dev/null 2>&1; then
        local escaped_error="${LAST_ERROR_MSG//\\/\\\\}"
        escaped_error="${escaped_error//\"/\\\"}"
        printf '{"status":"failed","contractVersion":"%s","error":"%s"}\n' \
            "${SCRIPT_CONTRACT_VERSION}" "${escaped_error}"
        return
    fi
    local jq_flags=(-nM)
    [[ -t 2 ]] || jq_flags+=(-c)
    jq "${jq_flags[@]}" \
        --arg status "failed" \
        --arg contractVersion "${SCRIPT_CONTRACT_VERSION}" \
        --arg error "${LAST_ERROR_MSG}" \
        --arg fix "${LAST_ERROR_FIX}" \
        '{status: $status, contractVersion: $contractVersion, error: $error}
         + (if $fix != "" then {fix: $fix} else {} end)' 2>/dev/null || true
}

die() {
    LAST_ERROR_MSG="$1"
    LAST_ERROR_FIX="${2:-}"
    trap - ERR
    echo "..................................................." >&2
    echo "Error: ${LAST_ERROR_MSG}" >&2
    [[ -z "${LAST_ERROR_FIX}" ]] || echo "Fix: ${LAST_ERROR_FIX}" >&2
    print_failure_json
    exit 1
}

on_error() {
    die "Unexpected failure at line $1."
}

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

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

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

trust_statement_sid() {
    local prefix="$1" region="$2" principal="$3" principal_label="Internal"
    if [[ "${principal}" == *.amazonaws.com ]]; then
        principal_label="Prod"
    fi
    printf '%s' "${prefix}${region}${principal_label}" | tr -cd '[:alnum:]'
}

WORK_DIR=""
setup_work_dir() {
    WORK_DIR="$(mktemp -d "${TMPDIR:-/tmp}/cloudwatch-pipeline-writer.XXXXXX")" ||
        die "Failed to create a private working directory."
    trap 'rm -rf -- "${WORK_DIR}"' EXIT
}

READ_OPTIONAL_JSON=""
read_optional_aws_json() {
    local label="$1" out_file error_file error_output status=0
    shift
    out_file=$(mktemp "${WORK_DIR}/out.XXXXXX") ||
        die "Failed to create a temporary file to inspect ${label}."
    error_file=$(mktemp "${WORK_DIR}/error.XXXXXX") ||
        die "Failed to create a temporary file to inspect ${label}."
    if "$@" >"${out_file}" 2>"${error_file}"; then
        status=0
    else
        status=$?
    fi
    error_output=$(cat -- "${error_file}")
    if [[ ${status} -eq 0 ]]; then
        READ_OPTIONAL_JSON=$(cat -- "${out_file}")
        echo "${READ_OPTIONAL_JSON}" | jq -e . >/dev/null || die "Reading ${label} returned invalid JSON."
    elif grep -qi 'NoSuchEntity' <<< "${error_output}"; then
        READ_OPTIONAL_JSON=""
    else
        die "Failed to inspect ${label}: ${error_output}" \
            "Re-run with the same flags; the rerun adopts what already exists."
    fi
}

parse_args() {
    while [[ $# -gt 0 ]]; do
        case "$1" in
            --writer-role-arn) require_value "$1" "${2:-}"; WRITER_ROLE_ARN="$2"; shift 2 ;;
            --aws-region) require_value "$1" "${2:-}"; AWS_REGION="$2"; shift 2 ;;
            --pipeline-name) require_value "$1" "${2:-}"; PIPELINE_NAME="$2"; shift 2 ;;
            --log-group-name=*)
                LOG_GROUP_NAME="${1#*=}"
                [[ -n "${LOG_GROUP_NAME}" ]] || {
                    echo "Error: --log-group-name requires a value." >&2
                    usage
                }
                shift
                ;;
            --log-group-name) require_value "$1" "${2:-}"; LOG_GROUP_NAME="$2"; shift 2 ;;
            --dry-run) DRY_RUN=true; shift ;;
            -h | --help) usage 0 ;;
            *) echo "Error: unknown argument $1" >&2; usage ;;
        esac
    done
}

parse_role_arn() {
    local arn="$1"
    [[ "${arn}" =~ ^arn:([^:]+):iam::([0-9]{12}):role/(.+)$ ]] ||
        die_usage "The --writer-role-arn flag must be an IAM role ARN, such as arn:aws:iam::123456789012:role/CloudWatchAzureWriter."
    PARTITION="${BASH_REMATCH[1]}"
    ACCOUNT_ID="${BASH_REMATCH[2]}"
    local resource="${BASH_REMATCH[3]}"
    ROLE_NAME="${resource##*/}"
    [[ "${ROLE_NAME}" =~ ^[A-Za-z0-9+=,.@_-]{1,64}$ ]] ||
        die_usage "The writer role ARN is not valid; it cannot end with a trailing slash or empty segment."
    if [[ "${resource}" == */* ]]; then
        ROLE_PATH="/${resource%/*}/"
    else
        ROLE_PATH="/"
    fi
    EXPECTED_ROLE_ARN="arn:${PARTITION}:iam::${ACCOUNT_ID}:role${ROLE_PATH}${ROLE_NAME}"
}

validate_inputs() {
    [[ -n "${WRITER_ROLE_ARN}" ]] || { echo "Error: --writer-role-arn is required." >&2; usage; }
    [[ -n "${AWS_REGION}" ]] || { echo "Error: --aws-region is required." >&2; usage; }
    [[ -n "${PIPELINE_NAME}" ]] || { echo "Error: --pipeline-name is required." >&2; usage; }
    [[ -n "${LOG_GROUP_NAME}" ]] || { echo "Error: --log-group-name is required." >&2; usage; }

    parse_role_arn "${WRITER_ROLE_ARN}"
    [[ "${PARTITION}" == "aws" ]] ||
        die_usage "The --writer-role-arn flag must be a commercial-partition (aws) IAM role ARN; GovCloud and China partitions are not supported."

    AWS_REGION="$(lower "${AWS_REGION}")"
    [[ "${AWS_REGION}" =~ ^[a-z0-9-]+$ ]] || die_usage "The --aws-region flag must look like a Region, such as us-east-1."

    [[ "${PIPELINE_NAME}" =~ ^[a-z][a-z0-9-]{2,27}$ ]] ||
        die_usage "The --pipeline-name flag must be 3-28 characters, lowercase letters, digits, and hyphens, starting with a letter."

    [[ ${#LOG_GROUP_NAME} -le ${LOG_GROUP_NAME_MAX_LENGTH} && "${LOG_GROUP_NAME}" =~ ^[${LOG_GROUP_NAME_CHARSET}]+$ ]] ||
        die_usage "The --log-group-name flag must be 1-${LOG_GROUP_NAME_MAX_LENGTH} characters using only letters, numbers, and ._/#-."
    [[ "${LOG_GROUP_NAME}" != "${LOG_GROUP_RESERVED_PREFIX}"* ]] ||
        die_usage "The --log-group-name flag cannot start with the reserved ${LOG_GROUP_RESERVED_PREFIX} prefix."
}

guard_caller_identity() {
    local identity_json id_file err_file err_output status=0 caller_account caller_arn caller_partition
    id_file=$(mktemp "${WORK_DIR}/identity-out.XXXXXX") ||
        die "Failed to create a temporary file to read the signed-in AWS identity."
    err_file=$(mktemp "${WORK_DIR}/identity-error.XXXXXX") ||
        die "Failed to create a temporary file to read the signed-in AWS identity."
    if aws sts get-caller-identity --output json >"${id_file}" 2>"${err_file}"; then
        status=0
    else
        status=$?
    fi
    err_output=$(cat -- "${err_file}")
    [[ ${status} -eq 0 ]] ||
        die "Failed to read the signed-in AWS identity: ${err_output}" \
            "Run 'aws configure' or set AWS credentials, then re-run this command."
    identity_json=$(cat -- "${id_file}")
    caller_account=$(printf '%s' "${identity_json}" | jq -r '.Account')
    caller_arn=$(printf '%s' "${identity_json}" | jq -r '.Arn')
    caller_partition=$(printf '%s' "${caller_arn}" | jq -R -r 'split(":")[1] // ""')
    if [[ "${caller_account}" != "${ACCOUNT_ID}" || "${caller_partition}" != "${PARTITION}" ]]; then
        die "The signed-in AWS credentials (account ${caller_account}) do not match the writer role's account ${ACCOUNT_ID} or partition ${PARTITION}." \
            "Sign in with credentials for that account and partition, then re-run this command."
    fi
}

build_expected_documents() {
    TRUST_SID="$(trust_statement_sid "CloudWatchAzurePipeline" "${AWS_REGION}" "${SERVICE_PRINCIPAL}")"
    EXPECTED_TRUST_STATEMENT="$(jq -cn --arg sid "${TRUST_SID}" --arg principal "${SERVICE_PRINCIPAL}" \
        '{Sid: $sid, Effect: "Allow", Principal: {Service: $principal}, Action: "sts:AssumeRole"}')"

    LOG_GROUP_ARN="arn:${PARTITION}:logs:${AWS_REGION}:${ACCOUNT_ID}:log-group:${LOG_GROUP_NAME}:*"
    EXPECTED_POLICY="$(jq -cn --arg region "${AWS_REGION}" --arg logGroupArn "${LOG_GROUP_ARN}" '
        {
            Version: "2012-10-17",
            Statement: [
                {Effect: "Allow", Action: ["logs:CreateLogStream", "logs:PutLogEvents"],
                 Resource: [$logGroupArn]},
                {Effect: "Allow", Action: "cloudwatch:PutMetricData", Resource: "*",
                 Condition: {StringEquals: {"aws:RequestedRegion": $region}}},
                {Effect: "Allow", Action: ["xray:PutTraceSegments", "xray:PutTelemetryRecords"], Resource: "*",
                 Condition: {StringEquals: {"aws:RequestedRegion": $region}}}
            ]
        }')"

    POLICY_NAME="CloudWatchAzureWrite-${PIPELINE_NAME}"
}

ensure_role_trust() {
    local role_json actual_path match_count
    read_optional_aws_json "IAM role ${ROLE_NAME}" aws iam get-role --role-name "${ROLE_NAME}" --output json
    role_json="${READ_OPTIONAL_JSON}"
    if [[ -z "${role_json}" ]]; then
        ROLE_EXISTS=false
        return 0
    fi
    ROLE_EXISTS=true

    actual_path=$(echo "${role_json}" | jq -r '.Role.Path')
    [[ "${actual_path}" == "${ROLE_PATH}" ]] ||
        die "An IAM role named ${ROLE_NAME} already exists at path ${actual_path}, not ${ROLE_PATH}." \
            "Use the role at that path, or choose a different role name."

    EXISTING_TRUST_DOC=$(echo "${role_json}" | jq -c '.Role.AssumeRolePolicyDocument')
    local existing_statement
    existing_statement=$(echo "${EXISTING_TRUST_DOC}" | jq -c --arg sid "${TRUST_SID}" '
        (.Statement // []) as $existing
        | ($existing | if type == "array" then . else [.] end) as $statements
        | [$statements[] | select(.Sid == $sid)]
        ')
    match_count=$(echo "${existing_statement}" | jq 'length')
    if [[ "${match_count}" -eq 0 ]]; then
        TRUST_STATUS="update"
    elif [[ "${match_count}" -eq 1 ]] &&
        [[ "$(echo "${existing_statement}" | jq -Sc '.[0]')" == "$(echo "${EXPECTED_TRUST_STATEMENT}" | jq -Sc .)" ]]; then
        TRUST_STATUS="existing"
    else
        die "Role ${ROLE_NAME} has a trust statement with Sid ${TRUST_SID} that differs from what this pipeline needs." \
            "In the console, choose Create new, or a different existing role, under Writer role in Review default configurations, then run the writer role script again."
    fi
}

apply_role_trust() {
    if [[ "${ROLE_EXISTS}" == false ]]; then
        if [[ "${DRY_RUN}" == true ]]; then
            log "Would create IAM role ${ROLE_NAME}."
            return 0
        fi
        local trust_policy create_args
        trust_policy=$(jq -cn --argjson statement "${EXPECTED_TRUST_STATEMENT}" '{Version: "2012-10-17", Statement: [$statement]}')
        create_args=(--role-name "${ROLE_NAME}" --assume-role-policy-document "${trust_policy}")
        [[ "${ROLE_PATH}" == "/" ]] || create_args+=(--path "${ROLE_PATH}")
        aws iam create-role "${create_args[@]}" >/dev/null ||
            die "Failed to create IAM role ${ROLE_NAME}."
        TRUST_RESULT="created"
        log "IAM role ${ROLE_NAME} (created)."
        return 0
    fi

    case "${TRUST_STATUS}" in
        existing)
            TRUST_RESULT="existing"
            log "Trust statement ${TRUST_SID} on role ${ROLE_NAME} (existing)."
            ;;
        update)
            if [[ "${DRY_RUN}" == true ]]; then
                log "Would add trust statement ${TRUST_SID} to role ${ROLE_NAME}."
            else
                local merged_trust
                merged_trust=$(echo "${EXISTING_TRUST_DOC}" | jq -c --argjson statement "${EXPECTED_TRUST_STATEMENT}" '
                    (.Statement // []) as $existing
                    | .Statement = (($existing | if type == "array" then . else [.] end) + [$statement])
                    ')
                aws iam update-assume-role-policy --role-name "${ROLE_NAME}" --policy-document "${merged_trust}" >/dev/null ||
                    die "Failed to update the trust policy for role ${ROLE_NAME}."
                TRUST_RESULT="updated"
                log "Trust statement ${TRUST_SID} added to role ${ROLE_NAME}."
            fi
            ;;
    esac
}

policy_is_recognized() {
    echo "${EXISTING_POLICY}" | jq -e \
        --arg prefix "arn:${PARTITION}:logs:${AWS_REGION}:${ACCOUNT_ID}:log-group:" \
        --arg charsetPattern "^[${LOG_GROUP_NAME_CHARSET}]{1,${LOG_GROUP_NAME_MAX_LENGTH}}\$" \
        --arg reservedPrefix "${LOG_GROUP_RESERVED_PREFIX}" \
        --argjson expected "${EXPECTED_POLICY}" '
        . as $policy
        | ($policy.Statement[0].Resource) as $resources
        | ($policy | del(.Statement[0].Resource)) as $policyShape
        | ($expected | del(.Statement[0].Resource)) as $expectedShape
        | ($resources | type == "array" and length >= 1)
          and (($resources | unique | length) == ($resources | length))
          and all(
            $resources[];
            type == "string"
            and startswith($prefix)
            and (
              ltrimstr($prefix)
              | endswith(":*")
              and (
                rtrimstr(":*") as $name
                | ($name | test($charsetPattern))
                and ($name | startswith($reservedPrefix) | not)
              )
            )
          )
          and (
            $policyShape == $expectedShape
            or (
              $policyShape == (
                $expected
                | del(.Statement[0].Resource, .Statement[1].Condition, .Statement[2].Condition)
              )
            )
          )
        ' >/dev/null
}

ensure_inline_policy() {
    if [[ "${ROLE_EXISTS}" == false ]]; then
        POLICY_STATUS="attach"
        return 0
    fi
    local policy_json resources
    read_optional_aws_json "inline policy ${POLICY_NAME} on role ${ROLE_NAME}" \
        aws iam get-role-policy --role-name "${ROLE_NAME}" --policy-name "${POLICY_NAME}" --output json
    policy_json="${READ_OPTIONAL_JSON}"
    if [[ -z "${policy_json}" ]]; then
        POLICY_STATUS="attach"
        return 0
    fi
    EXISTING_POLICY=$(echo "${policy_json}" | jq -c '.PolicyDocument')
    policy_is_recognized ||
        die "Inline policy ${POLICY_NAME} already exists on role ${ROLE_NAME} with different content." \
            "In the console, choose Create new, or a different existing role, under Writer role in Review default configurations, then run the writer role script again."

    resources=$(echo "${EXISTING_POLICY}" | jq -c '.Statement[0].Resource')
    if ! echo "${resources}" | jq -e --arg logGroupArn "${LOG_GROUP_ARN}" \
        'index($logGroupArn) != null' >/dev/null; then
        resources=$(echo "${resources}" | jq -c --arg logGroupArn "${LOG_GROUP_ARN}" '. + [$logGroupArn]')
        POLICY_ADDS_LOG_GROUP=true
    fi
    EXPECTED_POLICY=$(echo "${EXPECTED_POLICY}" | jq -c --argjson resources "${resources}" \
        '.Statement[0].Resource = $resources')

    if [[ "$(echo "${EXISTING_POLICY}" | jq -Sc .)" == "$(echo "${EXPECTED_POLICY}" | jq -Sc .)" ]]; then
        POLICY_STATUS="existing"
    else
        POLICY_STATUS="update"
    fi
}

apply_inline_policy() {
    case "${POLICY_STATUS}" in
        existing)
            POLICY_RESULT="existing"
            log "Inline policy ${POLICY_NAME} on role ${ROLE_NAME} (existing)."
            ;;
        attach | update)
            if [[ "${DRY_RUN}" == true ]]; then
                if [[ "${POLICY_STATUS}" == "attach" ]]; then
                    log "Would attach inline policy ${POLICY_NAME} to role ${ROLE_NAME}."
                elif [[ "${POLICY_ADDS_LOG_GROUP}" == true ]]; then
                    log "Would add ${LOG_GROUP_NAME} to inline policy ${POLICY_NAME} on role ${ROLE_NAME}."
                else
                    log "Would update inline policy ${POLICY_NAME} on role ${ROLE_NAME} without removing existing log groups."
                fi
            else
                aws iam put-role-policy --role-name "${ROLE_NAME}" --policy-name "${POLICY_NAME}" \
                    --policy-document "${EXPECTED_POLICY}" >/dev/null ||
                    die "Failed to write the ${POLICY_NAME} policy on role ${ROLE_NAME}."
                if [[ "${POLICY_STATUS}" == "attach" ]]; then
                    POLICY_RESULT="created"
                    log "Inline policy ${POLICY_NAME} attached to role ${ROLE_NAME}."
                else
                    POLICY_RESULT="updated"
                    log "Inline policy ${POLICY_NAME} on role ${ROLE_NAME} (updated)."
                fi
            fi
            ;;
    esac
}

print_plan() {
    local role_action role_plan policy_plan
    if [[ "${ROLE_EXISTS}" == false ]]; then
        role_action="creates"
        role_plan="will be created"
    else
        role_action="updates"
        if [[ "${TRUST_STATUS}" == "update" ]]; then
            role_plan="exists, will be updated to add the missing trust statement"
        else
            role_plan="exists, already has what it needs"
        fi
    fi
    case "${POLICY_STATUS}" in
        attach) policy_plan="will be attached" ;;
        update)
            if [[ "${POLICY_ADDS_LOG_GROUP}" == true ]]; then
                policy_plan="will add ${LOG_GROUP_NAME} without removing existing log groups"
            else
                policy_plan="will be updated without removing existing log groups"
            fi
            ;;
        *) policy_plan="already matches" ;;
    esac
    cat >&2 <<EOF

This ${role_action} the IAM role at ${EXPECTED_ROLE_ARN}:

  Role: ${role_plan}
  Inline policy ${POLICY_NAME}: ${policy_plan}
EOF
}

confirm() {
    local reply discarded

    [[ -t 0 ]] || return 0

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

    printf 'Continue? [Enter to continue, Ctrl-C to abort] ' >&2
    if ! read -r reply; then
        echo >&2
        die "Aborted."
    fi
    echo >&2
    if [[ -n "${reply}" && ! "${reply}" =~ ^[Yy]([Ee][Ss])?$ ]]; then
        die "Aborted at confirmation."
    fi
}

print_result() {
    local jq_flags=(-nM)
    [[ -t 2 ]] || jq_flags+=(-c)
    jq "${jq_flags[@]}" \
        --arg status "succeeded" \
        --arg contractVersion "${SCRIPT_CONTRACT_VERSION}" \
        --arg region "${AWS_REGION}" \
        --arg arn "${EXPECTED_ROLE_ARN}" \
        --arg trust "${TRUST_RESULT}" \
        --arg policy "${POLICY_RESULT}" \
        --arg policyName "${POLICY_NAME}" \
        --arg logGroupArn "${LOG_GROUP_ARN}" \
        '{status: $status, contractVersion: $contractVersion, region: $region,
          writerRole: {arn: $arn, trust: $trust, policy: $policy},
          policyName: $policyName, logGroupArn: $logGroupArn}'
}

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

    parse_args "$@"
    validate_inputs

    command -v aws >/dev/null 2>&1 || die "The AWS CLI is required."
    command -v jq >/dev/null 2>&1 || die "The jq command is required."

    setup_work_dir
    guard_caller_identity
    build_expected_documents
    ensure_role_trust
    ensure_inline_policy

    if [[ "${DRY_RUN}" == false ]]; then
        print_plan
        confirm
    fi

    apply_role_trust
    apply_inline_policy

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

    log "Writer role ${EXPECTED_ROLE_ARN} (trust: ${TRUST_RESULT}, policy: ${POLICY_RESULT})."
    echo "..................................................." >&2
    print_result
}

main "$@"
