#!/usr/bin/env bash
# Automatum Azure — two-app Entra setup (Workload Identity Federation, no secrets).
#
# Adapted from the Suger single-app/client-secret script. Automatum uses TWO
# single-tenant Entra apps and Workload Identity Federation (WIF). No client
# secret is ever created or stored.
#
# What this configures in the target tenant:
#   App 1 — "Cloud Account (transact)"  → landing page + Marketplace fulfillment
#     - Single tenant, NO API permissions, NO admin consent
#     - Marketplace SaaS Fulfillment API service principal present in the tenant
#     - One federated credential (WIF)
#   App 2 — "Co-Sell (integrations)"    → Microsoft Partner Center referrals
#     - Single tenant, Web redirect URI = Automatum callback
#     - 3 delegated permissions (Graph User.Read + 2 Partner APIs user_impersonation)
#     - Admin consent granted (Global Administrator required)
#     - One federated credential (WIF)
#
# NOT automatable here (Partner Center, not Entra — the script prints reminders):
#   - Create your own dedicated integration user in Partner Center with the Referrals Admin role
#   - Add the Co-Sell app under Partner Center > User management > Azure AD applications
#   - Grant the Transact app access in Partner Center + set offer Technical Configuration
#
# ⚠️ WIF values (Issuer / Subject / Audience / Name) MUST match exactly what the
#    Automatum UI shows on the relevant card:
#      - Transact:  Settings > Cloud Accounts > Azure card
#      - Co-Sell:   Settings > Integrations > Azure Partner Center card
#    The defaults below are the published production values. Override per app with
#    the *_FIC_* environment variables if the UI shows different values.
#
# Prerequisites (auto-detected):
#   - Azure CLI (az) + jq. If missing, the script prints install commands.
#   - Azure login: if not signed in, the script runs `az login`.
#   - The executor must be a Global Administrator in the target tenant
#     (required to grant admin consent for the Co-Sell app).
#
# Usage:
#   ./setup-azure-apps.sh
#
#   # Re-run safely — every step is idempotent (reuses same-named apps,
#   # skips existing federated credentials, re-applies permissions/consent).
#
#   # Advanced overrides (rarely needed):
#   TRANSACT_APP_NAME="..." COSELL_APP_NAME="..." ./setup-azure-apps.sh
#   COSELL_FIC_SUBJECT="automatum-cosell" ./setup-azure-apps.sh

# -u has quirks with heredoc/command substitution on macOS bash 5.2; keep -e + pipefail only.
set -eo pipefail

# ---- Configuration ----------------------------------------------------------
TRANSACT_APP_NAME="${TRANSACT_APP_NAME:-Automatum Cloud Account}"
COSELL_APP_NAME="${COSELL_APP_NAME:-Automatum Co-Sell}"
# Optional: YOUR dedicated Partner Center integration user (a service account, not a
# person's mailbox). You create this in YOUR Partner Center — the script only prints a
# reminder. Set it to have the reminder name it; leave blank for generic guidance.
INTEGRATION_USER_UPN="${INTEGRATION_USER_UPN:-}"
OUTPUT_FILE="${OUTPUT_FILE:-./automatum-azure-apps.txt}"

# Co-Sell app: Web redirect URI (auth-code flow). Do NOT use the SPA platform —
# it fails the authorize step with AADSTS900561 ("endpoint only accepts POST").
COSELL_REDIRECT_URI="${COSELL_REDIRECT_URI:-https://api.automatum.io/integration/azure-partner-center/callback}"

# Workload Identity Federation values — defaults are the published production values.
# Confirm against the Automatum card for each connection before relying on them.
TRANSACT_FIC_NAME="${TRANSACT_FIC_NAME:-automatum}"
TRANSACT_FIC_ISSUER="${TRANSACT_FIC_ISSUER:-https://api.automatum.io}"
TRANSACT_FIC_SUBJECT="${TRANSACT_FIC_SUBJECT:-automatum}"
TRANSACT_FIC_AUDIENCE="${TRANSACT_FIC_AUDIENCE:-api://AzureADTokenExchange}"

COSELL_FIC_NAME="${COSELL_FIC_NAME:-automatum}"
COSELL_FIC_ISSUER="${COSELL_FIC_ISSUER:-https://api.automatum.io}"
COSELL_FIC_SUBJECT="${COSELL_FIC_SUBJECT:-automatum}"
COSELL_FIC_AUDIENCE="${COSELL_FIC_AUDIENCE:-api://AzureADTokenExchange}"

# Well-known Microsoft resource IDs in the public directory.
MARKETPLACE_SAAS_RESOURCE_ID="20e940b3-4c77-4b0b-9a53-9e16a1b010a7"   # Marketplace SaaS Fulfillment API
MICROSOFT_PARTNER_RESOURCE_ID="4990cffe-04e8-4e8b-808a-1175604b879f"  # Microsoft Partner (api.partnercenter.microsoft.com)
PARTNER_CENTER_RESOURCE_ID_1="fa3d9a0c-3fb0-42cc-9193-47c7ecd2edbd"   # Microsoft Partner Center (Referrals)
GRAPH_RESOURCE_ID="00000003-0000-0000-c000-000000000000"             # Microsoft Graph
GRAPH_USER_READ_SCOPE_ID="e1fe6dd8-ba31-4d61-89e7-88639da4683d"      # Graph User.Read

# Partner APIs that need user_impersonation on the Co-Sell app.
PARTNER_RESOURCE_IDS=(
  "$MICROSOFT_PARTNER_RESOURCE_ID"
  "$PARTNER_CENTER_RESOURCE_ID_1"
)

# ---- Preflight --------------------------------------------------------------
detect_os() {
  case "$(uname -s)" in
    Darwin*) echo "macos" ;;
    Linux*)
      if grep -qiE 'ubuntu|debian' /etc/os-release 2>/dev/null; then echo "debian"
      elif grep -qiE 'rhel|centos|fedora|rocky|alma' /etc/os-release 2>/dev/null; then echo "rhel"
      else echo "linux"; fi ;;
    MINGW*|CYGWIN*|MSYS*) echo "windows" ;;
    *) echo "unknown" ;;
  esac
}

missing_tools=()
command -v az >/dev/null 2>&1 || missing_tools+=("az")
command -v jq >/dev/null 2>&1 || missing_tools+=("jq")
if (( ${#missing_tools[@]} > 0 )); then
  echo "❌ Missing tools: ${missing_tools[*]}"
  echo
  echo "📦 Easiest option: Azure Cloud Shell (browser-based, no install, auto-signed-in)"
  echo "   → Open https://shell.azure.com, choose Bash, upload this script and run it"
  echo
  echo "To install locally:"
  case "$(detect_os)" in
    macos)   echo "   brew install azure-cli jq" ;;
    debian)  echo "   curl -sL https://aka.ms/InstallAzureCLIDeb | sudo bash"; echo "   sudo apt-get install -y jq" ;;
    rhel)    echo "   sudo dnf install -y azure-cli jq" ;;
    windows) echo "   Install WSL then follow the debian steps, or https://aka.ms/installazurecliwindows" ;;
    *)       echo "   https://learn.microsoft.com/cli/azure/install-azure-cli" ;;
  esac
  exit 1
fi

# Filter WARNING noise but keep real errors.
run_az() {
  local out rc tmperr
  tmperr=$(mktemp)
  if out=$(az "$@" 2>"$tmperr"); then
    grep -v "^WARNING" "$tmperr" >&2 || true
    rm -f "$tmperr"; printf '%s' "$out"; return 0
  else
    rc=$?; cat "$tmperr" >&2; rm -f "$tmperr"; return $rc
  fi
}

wait_for_sp() {
  local id="$1" label="$2" i
  for i in $(seq 1 15); do
    if az ad sp show --id "$id" >/dev/null 2>&1; then return 0; fi
    sleep 2
  done
  echo "❌ Timed out waiting for $label service principal (id=$id)" >&2
  return 1
}

ensure_sp() {
  local rid="$1"
  if az ad sp show --id "$rid" >/dev/null 2>&1; then
    echo "    SP $rid already present" >&2
  else
    run_az ad sp create --id "$rid" >/dev/null
    echo "    SP $rid created" >&2
  fi
  wait_for_sp "$rid" "$rid" >&2
}

# Create or reuse a single-tenant app. $2 = redirect URI (empty for none).
# Progress goes to stderr; the appId is printed to stdout for capture.
create_app() {
  local name="$1" redirect="$2" app_id
  app_id=$(az ad app list --display-name "$name" --query "[0].appId" -o tsv 2>/dev/null || true)
  if [[ -n "$app_id" ]]; then
    echo "    Reusing '$name' (appId=$app_id)" >&2
    if [[ -n "$redirect" ]]; then
      run_az ad app update --id "$app_id" --sign-in-audience AzureADMyOrg --web-redirect-uris "$redirect" >/dev/null
    else
      run_az ad app update --id "$app_id" --sign-in-audience AzureADMyOrg >/dev/null
    fi
  else
    if [[ -n "$redirect" ]]; then
      app_id=$(run_az ad app create --display-name "$name" --sign-in-audience AzureADMyOrg \
        --web-redirect-uris "$redirect" --is-fallback-public-client false --query appId -o tsv)
    else
      app_id=$(run_az ad app create --display-name "$name" --sign-in-audience AzureADMyOrg \
        --is-fallback-public-client false --query appId -o tsv)
    fi
    run_az ad sp create --id "$app_id" >/dev/null
    echo "    Created '$name' (appId=$app_id)" >&2
  fi
  wait_for_sp "$app_id" "$name" >&2
  printf '%s' "$app_id"
}

# Idempotent federated credential (Workload Identity Federation).
add_federated_credential() {
  local app_id="$1" name="$2" issuer="$3" subject="$4" audience="$5" existing
  existing=$(az ad app federated-credential list --id "$app_id" \
    --query "[?name=='$name'].name | [0]" -o tsv 2>/dev/null || true)
  if [[ -n "$existing" ]]; then
    echo "    Federated credential '$name' already exists — skipping" >&2
    return 0
  fi
  run_az ad app federated-credential create --id "$app_id" \
    --parameters "{\"name\":\"$name\",\"issuer\":\"$issuer\",\"subject\":\"$subject\",\"audiences\":[\"$audience\"]}" >/dev/null
  echo "    Federated credential '$name' added ✓" >&2
}

add_cosell_permissions() {
  local app_id="$1" rid scope_id
  # Microsoft Graph User.Read (portal adds this by default; CLI does not).
  run_az ad app permission add --id "$app_id" --api "$GRAPH_RESOURCE_ID" \
    --api-permissions "${GRAPH_USER_READ_SCOPE_ID}=Scope" >/dev/null
  echo "    Microsoft Graph User.Read ✓" >&2
  # 2 Partner APIs: user_impersonation (delegated).
  for rid in "${PARTNER_RESOURCE_IDS[@]}"; do
    scope_id=$(az ad sp show --id "$rid" \
      --query "oauth2PermissionScopes[?value=='user_impersonation'].id | [0]" -o tsv 2>/dev/null || true)
    if [[ -n "$scope_id" ]]; then
      run_az ad app permission add --id "$app_id" --api "$rid" \
        --api-permissions "${scope_id}=Scope" >/dev/null
      echo "    $rid user_impersonation ✓" >&2
    else
      echo "    ⚠️  $rid does not expose user_impersonation, skipping" >&2
    fi
  done
}

grant_admin_consent() {
  local app_id="$1" i rid scope
  local ok=false
  for i in $(seq 1 10); do
    if run_az ad app permission admin-consent --id "$app_id" >/dev/null 2>&1; then ok=true; break; fi
    sleep 3
  done
  if ! $ok; then
    echo "❌ admin-consent failed. Common causes:" >&2
    echo "   - The current account is not a Global Administrator" >&2
    echo "   - The tenant has disabled user/app consent" >&2
    return 1
  fi
  # az quirk: admin-consent can return 0 without creating the OAuth2 grant. Apply explicit grant as a fallback.
  sleep 3
  for rid in "$GRAPH_RESOURCE_ID" "${PARTNER_RESOURCE_IDS[@]}"; do
    scope="user_impersonation"
    [[ "$rid" == "$GRAPH_RESOURCE_ID" ]] && scope="User.Read"
    run_az ad app permission grant --id "$app_id" --api "$rid" --scope "$scope" >/dev/null 2>&1 || true
  done
  echo "    admin-consent + explicit grant complete ✓" >&2
}

# ---- Context ----------------------------------------------------------------
echo "==> Current Azure context"
if ! az account show >/dev/null 2>&1; then
  echo "⚠️  Not signed in to Azure — invoking az login..."
  echo "    (For headless shells: az login --use-device-code --tenant <tenant-id>)"
  az login || { echo "❌ Login failed or cancelled"; exit 1; }
fi
az account show --query "{tenantId: tenantId, subscription: name, user: user.name}" -o table
TENANT_ID=$(az account show --query tenantId -o tsv)
read -r -p "Create/update the two Automatum apps in this tenant? [y/N] " ans
[[ "$ans" =~ ^[Yy]$ ]] || { echo "Cancelled"; exit 1; }

# ---- App 1: Cloud Account (transact) ---------------------------------------
echo
echo "==> App 1/2: $TRANSACT_APP_NAME (landing page + Marketplace fulfillment)"
TRANSACT_APP_ID=$(create_app "$TRANSACT_APP_NAME" "")
echo "    Marketplace SaaS Fulfillment API — ensuring service principal exists"
ensure_sp "$MARKETPLACE_SAAS_RESOURCE_ID"
echo "    No API permissions / no admin consent needed for the transact app"
add_federated_credential "$TRANSACT_APP_ID" \
  "$TRANSACT_FIC_NAME" "$TRANSACT_FIC_ISSUER" "$TRANSACT_FIC_SUBJECT" "$TRANSACT_FIC_AUDIENCE"

# ---- App 2: Co-Sell (integrations) -----------------------------------------
echo
echo "==> App 2/2: $COSELL_APP_NAME (Microsoft Partner Center referrals)"
COSELL_APP_ID=$(create_app "$COSELL_APP_NAME" "$COSELL_REDIRECT_URI")
echo "    Pre-creating service principals for the Partner APIs"
for rid in "${PARTNER_RESOURCE_IDS[@]}"; do ensure_sp "$rid"; done
echo "    Adding API permissions"
add_cosell_permissions "$COSELL_APP_ID"
echo "    Granting admin consent (Global Administrator required)"
grant_admin_consent "$COSELL_APP_ID" || exit 1
add_federated_credential "$COSELL_APP_ID" \
  "$COSELL_FIC_NAME" "$COSELL_FIC_ISSUER" "$COSELL_FIC_SUBJECT" "$COSELL_FIC_AUDIENCE"

# ---- Summary ----------------------------------------------------------------
umask 077
cat > "$OUTPUT_FILE" <<EOF
# Automatum Azure apps (generated $(date -u +%Y-%m-%dT%H:%M:%SZ))
# No secrets — both apps use Workload Identity Federation.
TENANT_ID="$TENANT_ID"

TRANSACT_APP_NAME="$TRANSACT_APP_NAME"
TRANSACT_APP_ID="$TRANSACT_APP_ID"

COSELL_APP_NAME="$COSELL_APP_NAME"
COSELL_APP_ID="$COSELL_APP_ID"
COSELL_REDIRECT_URI="$COSELL_REDIRECT_URI"
EOF
chmod 600 "$OUTPUT_FILE"

cat <<EOF

================================================================
✅ Entra-side setup complete. No secrets were created (WIF only).
================================================================

  Tenant ID:              $TENANT_ID

  App 1 — Cloud Account (transact / landing page)
    Application ID:       $TRANSACT_APP_ID
    Federated credential: $TRANSACT_FIC_NAME  (subject=$TRANSACT_FIC_SUBJECT)

  App 2 — Co-Sell (integrations)
    Application ID:       $COSELL_APP_ID
    Redirect URI (Web):   $COSELL_REDIRECT_URI
    Federated credential: $COSELL_FIC_NAME  (subject=$COSELL_FIC_SUBJECT)

  📁 Saved (mode 600) to: $OUTPUT_FILE

----------------------------------------------------------------
Manual steps in Partner Center (cannot be done with az):
----------------------------------------------------------------
  1. Create a dedicated co-sell integration user in YOUR Partner Center:
       Settings > User management > Add user
       Use a service account, not a personal mailbox${INTEGRATION_USER_UPN:+ (e.g. $INTEGRATION_USER_UPN)}.
       Assign the Referrals Admin role (entire organization).
  2. Grant the Transact app access in Partner Center (Manager role) and
     set the offer Technical Configuration:
       Microsoft Entra tenant ID:      $TENANT_ID
       Microsoft Entra application ID: $TRANSACT_APP_ID
       Landing page URL + Connection webhook: use the values from the
         Automatum Cloud Account (Azure) card.

----------------------------------------------------------------
Confirm in Automatum, then Test Configuration on each card:
----------------------------------------------------------------
  - Transact: Settings > Cloud Accounts > Azure
  - Co-Sell:  Settings > Integrations > Azure Partner Center

⚠️ If the WIF Issuer/Subject/Audience printed above differ from what a card
   shows, re-run with the matching *_FIC_* environment variables.
================================================================
EOF
