#!/bin/sh
# Creates the Entra app registration "Robobox" (infrastructure item I-1,
# docs/plan/infrastructure.md). Run it after `az login` into the tenant that
# owns the mailbox. A client tenant runs the same script.
#
# The app is a public client with no secret, on the "Mobile and desktop
# applications" platform with the redirect URI http://localhost. It asks for
# the delegated Graph scopes Mail.ReadWrite, offline_access and User.Read. It
# accepts accounts of this tenant only, so set `mail.tenant` to the tenant ID.
# The script grants no consent: the mailbox user consents at the first sign-in.
set -eu

NAME="${1:-Robobox}"
GRAPH=00000003-0000-0000-c000-000000000000

if [ -n "$(az ad app list --display-name "$NAME" --query '[].appId' -o tsv)" ]; then
  echo "An app named \"$NAME\" exists already. Nothing changed." >&2
  exit 1
fi

scope_id() {
  az ad sp show --id "$GRAPH" --query "oauth2PermissionScopes[?value=='$1'].id | [0]" -o tsv
}

ACCESS=$(cat <<EOF
[{"resourceAppId":"$GRAPH","resourceAccess":[
  {"id":"$(scope_id Mail.ReadWrite)","type":"Scope"},
  {"id":"$(scope_id offline_access)","type":"Scope"},
  {"id":"$(scope_id User.Read)","type":"Scope"}]}]
EOF
)

APP_ID=$(az ad app create \
  --display-name "$NAME" \
  --sign-in-audience AzureADMyOrg \
  --public-client-redirect-uris http://localhost \
  --is-fallback-public-client true \
  --required-resource-accesses "$ACCESS" \
  --query appId -o tsv)

TENANT=$(az account show --query tenantId -o tsv)
echo "Created \"$NAME\"."
echo "mail.clientId: $APP_ID"
echo "mail.tenant:   $TENANT"
