#!/usr/bin/env bash
# OPTIONAL - for customers who prefer not to consent to SailPoint's "SailPoint CLI" app.
#
# Creates a single-tenant public-client app registration in YOUR tenant that the onboarding
# script uses for the admin's interactive sign-in. It holds no secret, no application
# permissions and no roles: it only lets the signed-in admin obtain delegated tokens for the
# Power Platform admin API and Dataverse for the duration of the script.
#
# Run as a user who can create app registrations, with az CLI signed in to your tenant:
#   az login --tenant <TENANT_ID>
#   ./New-CustomerSignInApp.sh "Entro Onboarding CLI"
# Then run the onboarding script with:  -PublicClientId <the printed appId>
set -euo pipefail

NAME="${1:-Entro Onboarding CLI}"

DYNAMICS_CRM_APP="00000007-0000-0000-c000-000000000000"    # Dynamics CRM / Dataverse
POWERAPPS_SERVICE_APP="475226c6-020e-4fb2-8a90-7a972cbfc1d4" # PowerApps Service (admin API)
GRAPH_APP="00000003-0000-0000-c000-000000000000"

echo "== creating single-tenant public client '$NAME'"
APP_ID=$(az ad app create \
  --display-name "$NAME" \
  --sign-in-audience AzureADMyOrg \
  --is-fallback-public-client true \
  --public-client-redirect-uris "https://login.microsoftonline.com/common/oauth2/nativeclient" \
  --query appId -o tsv)
echo "   appId = $APP_ID"

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

echo "== adding delegated permissions"
az ad app permission add --id "$APP_ID" --api "$DYNAMICS_CRM_APP"     --api-permissions "$(scope_id "$DYNAMICS_CRM_APP" user_impersonation)=Scope"
az ad app permission add --id "$APP_ID" --api "$POWERAPPS_SERVICE_APP" --api-permissions "$(scope_id "$POWERAPPS_SERVICE_APP" User)=Scope"
az ad app permission add --id "$APP_ID" --api "$GRAPH_APP"            --api-permissions "$(scope_id "$GRAPH_APP" offline_access)=Scope" "$(scope_id "$GRAPH_APP" openid)=Scope"

az ad sp create --id "$APP_ID" >/dev/null 2>&1 || true

echo "== granting admin consent (so the script's sign-in never prompts for consent)"
az ad app permission admin-consent --id "$APP_ID" || echo "   admin consent failed - a Global Admin can grant it in Entra > App registrations > $NAME > API permissions"

cat <<EOF

Done. Run the onboarding script with your own sign-in client:
  pwsh ./Entro-Copilot-Studio-Onboarding.ps1 -ClientId <ENTRO_APP_ID> -TenantId <TENANT_ID> -PublicClientId $APP_ID

You can delete this app registration after onboarding; Entro does not use it.
EOF
