#!/usr/bin/env bash
#
# Qry's Entra app registration: sign-in, optional group sync, optional queries
# to Azure Databricks as each person (OBO). Run by the customer's Entra
# administrator, once, with their own `az login`.
#
# Usage:
#   ./azure-entra-app.sh --qry-url https://qry.example.com \
#     [--name Qry] [--groups] [--databricks-obo] [--apply]
#
# Without --apply it prints every command and changes nothing. With it, it
# creates the app, grants admin consent and writes a client secret to
# ./qry-entra-secret.txt (mode 600) - never to the terminal.
#
# Afterwards: `qry doctor --plane prerequisites --entra-app-id <appId>
# --qry-url <url>` says whether anything is still missing.
set -euo pipefail

QRY_URL="" NAME="Qry" GROUPS_CLAIM=0 OBO=0 APPLY=0
while [[ $# -gt 0 ]]; do
  case "$1" in
    --qry-url) QRY_URL="${2%/}"; shift 2 ;;
    --name) NAME="$2"; shift 2 ;;
    --groups) GROUPS_CLAIM=1; shift ;;
    --databricks-obo) OBO=1; shift ;;
    --apply) APPLY=1; shift ;;
    -h|--help) sed -n '2,17p' "$0"; exit 0 ;;
    *) echo "unknown option $1" >&2; exit 2 ;;
  esac
done
[[ "$QRY_URL" == https://* ]] || { echo "--qry-url must be the https address Qry is served at" >&2; exit 2; }

GRAPH=00000003-0000-0000-c000-000000000000
# openid, profile, email, User.Read (delegated). Ids, because that is what the
# app manifest stores.
GRAPH_SCOPES="37f7f235-527c-4136-accd-4a02d197296e=Scope 14dad69e-099b-42c9-810b-d002981feec1=Scope 64a6cdd6-aab1-4aaf-94b8-3cc8405e90d0=Scope e1fe6dd8-ba31-4d61-89e7-88639da4683d=Scope"
DATABRICKS=2ff814a6-3304-4ab8-85cb-cd0e6f879c1d
DATABRICKS_IMPERSONATION="739272be-e143-11e8-9f32-f2801f1b9fd1=Scope"
REDIRECT="$QRY_URL/auth/azure/callback"

run() {
  echo "+ $*"
  if (( APPLY )); then "$@"; fi
}

SECRET_FILE="./qry-entra-secret.txt"
# The secret goes to a new file only: an existing one (or a symlink) could
# have wider permissions than this script would give it, or point elsewhere.
if (( APPLY )) && [[ -e "$SECRET_FILE" || -L "$SECRET_FILE" ]]; then
  echo "$SECRET_FILE already exists; move it away first" >&2; exit 1
fi

echo "# Entra app for Qry at $QRY_URL$( ((APPLY)) || echo ' (dry run: nothing is changed)')"
if (( APPLY )); then
  APP_ID=$(az ad app create --display-name "$NAME" --sign-in-audience AzureADMyOrg \
    --web-redirect-uris "$REDIRECT" --query appId -o tsv)
  echo "+ az ad app create --display-name $NAME ... -> $APP_ID"
else
  APP_ID="<appId>"
  echo "+ az ad app create --display-name $NAME --sign-in-audience AzureADMyOrg --web-redirect-uris $REDIRECT"
fi

# shellcheck disable=SC2086 # the scope list is meant to split
run az ad app permission add --id "$APP_ID" --api "$GRAPH" --api-permissions $GRAPH_SCOPES
if (( OBO )); then
  run az ad app permission add --id "$APP_ID" --api "$DATABRICKS" --api-permissions "$DATABRICKS_IMPERSONATION"
fi
if (( GROUPS_CLAIM )); then
  run az ad app update --id "$APP_ID" --set groupMembershipClaims=SecurityGroup
fi

# Consent needs the app's service principal in the tenant, and most tenants
# forbid people from consenting themselves: without this the first sign-in
# stops at "Need admin approval". `permission grant` rather than
# `admin-consent`: the latter can return without creating the grant.
run az ad sp create --id "$APP_ID"
run az ad app permission grant --id "$APP_ID" --api "$GRAPH" --scope "openid profile email User.Read"
if (( OBO )); then
  run az ad app permission grant --id "$APP_ID" --api "$DATABRICKS" --scope user_impersonation
fi

echo "+ az ad app credential reset --id $APP_ID --display-name qry --years 1 --append > $SECRET_FILE"
if (( APPLY )); then
  ( umask 077; set -o noclobber; az ad app credential reset --id "$APP_ID" --display-name qry \
      --years 1 --append --query password -o tsv > "$SECRET_FILE" )
fi

END="<one year from today>"
if (( APPLY )); then
  END=$(az ad app credential list --id "$APP_ID" \
    --query "sort_by([?displayName=='qry'], &endDateTime)[-1].endDateTime" -o tsv | cut -c1-10)
fi
TENANT=$(az account show --query tenantId -o tsv 2>/dev/null || echo "<tenantId>")
cat <<EOF

# For Admin > Authentication > Microsoft Entra ID in Qry:
#   Application (client) ID  $APP_ID
#   Directory (tenant) ID    $TENANT
#   Client secret            the content of $SECRET_FILE
#   Client secret expires on $END  (Qry tells administrators before that date)
#   Redirect URI             $REDIRECT
#
# Then check it:
#   qry doctor --plane prerequisites --entra-app-id $APP_ID --qry-url $QRY_URL
EOF
