Please help... updating aliases

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

Approach 2: Two-stage - create account first, then set aliases via update.

The account ID is read DIRECTLY from the create output (“Created Account ”)

instead of using a query. This guarantees that exactly one ID is present

 → no “bo\nba”, no HTTP 400.

CLI=“stalwart-cli”
URL=“https://example.com”
API_KEY=“API....”

echo “== Loading domains ==”

DOMAINS_OUTPUT=$(
$CLI --url “$URL” 
–api-key “$API_KEY” 
query Domain
)

echo “”
echo “Available domains:”
echo “--------------------”
echo “$DOMAINS_OUTPUT”
echo “”

read -rp "Account Name (name): " NAME
read -rp "Full Name: " FULL_NAME
read -rp "Domain ID: " DOMAIN_ID
read -rp "Aliases (comma-separated, empty = none): " ALIASES_INPUT

Build aliases as index-keyed map: {“0”:{…},“1”:{…}}

(Stalwart expects these collections as a map, NOT as an array - just like credentials.)

IFS=‘,’ read -ra ALIASES_ARRAY <<< “$ALIASES_INPUT”

ALIASES_JSON=“{”
idx=0
first=true
for alias in “${ALIASES_ARRAY[@]}”; do
alias=$(echo “$alias” | xargs)
[[ -z “$alias” ]] && continue

if [[ "$first" == true ]]; then
    first=false
else
    ALIASES_JSON+=","
fi

ALIASES_JSON+="\"$idx\":{\"name\":\"$alias\",\"domainId\":\"$DOMAIN_ID\",\"enabled\":true}"
idx=$((idx + 1))

done
ALIASES_JSON+=“}”

echo “Aliases JSON:”
echo “$ALIASES_JSON”

echo “== Creating account ==”

CREATE_OUTPUT=$(
$CLI --url “$URL” 
–api-key “$API_KEY” 
create Account/User 
–field “name=$NAME” 
–field “description=$FULL_NAME” 
–field “domainId=$DOMAIN_ID” 
–field ‘credentials={“0”:{“@type”:“Password”,“secret”:“AnfangsPasswort”}}’ 
–field ‘memberGroupIds={}’ 
–field ‘roles={“@type”:“User”}’ 
–field ‘permissions={“@type”:“Inherit”}’ 
–field ‘locale=de_DE’ 
–field ‘timeZone=Europe/Berlin’ 
–field ‘quotas={“maxDiskQuota”:524288000}’ 
–field ‘aliases={}’ 
–field ‘encryptionAtRest={“@type”:“Disabled”}’
)

echo “$CREATE_OUTPUT”

Extract ID from “Created Account ” → guaranteed to be a single value.

ACCOUNT_ID=$(echo “$CREATE_OUTPUT” | awk ‘/Created Account/ {print $NF; exit}’)

if [[ -z “$ACCOUNT_ID” ]]; then
echo “ERROR: Could not read account ID from create output.” >&2
exit 1
fi

echo “Account ID: $ACCOUNT_ID”

Only set aliases if any were provided

if [[ “$ALIASES_JSON” != “{}” ]]; then
echo “== Setting aliases ==”
$CLI --url “$URL” --api-key “$API_KEY” 
update Account “$ACCOUNT_ID” 
–field “aliases=$ALIASES_JSON”
echo “Aliases set.”
else
echo “No aliases provided - update skipped.”
fi