#!/usr/bin/env sh
# Asks Subcontext for an access token and prints the answer.
#
# An access token lets your code use the Subcontext API for two hours.
# You get one by sending your API application's client id
# and client secret to Subcontext (an OAuth "client credentials" request).
#
# Run it on your computer or your server, never in a web page:
#
#   SUBCONTEXT_CLIENT_ID=... SUBCONTEXT_CLIENT_SECRET=... sh get-token.sh
#
# SUBCONTEXT_CLIENT_ID and SUBCONTEXT_CLIENT_SECRET: from the Subcontext
#   dashboard, Integrations, API applications. The client secret is shown only
#   once, when you create the application (or rotate its secret).
# SUBCONTEXT_SCOPE (optional): what the token may do, separated by spaces.
#   Default "read". It can only include scopes ticked on the API application,
#   for example "read write crm".
# SUBCONTEXT_BASE_URL (optional): the Subcontext address. Default
#   https://subcontext.com.
#
# Needs curl. A good answer looks like:
#   {"access_token":"...","token_type":"Bearer","expires_in":7200,"scope":"read","created_at":...}

base_url="${SUBCONTEXT_BASE_URL:-https://subcontext.com}"
base_url="${base_url%/}"
scope="${SUBCONTEXT_SCOPE:-read}"

if [ -z "$SUBCONTEXT_CLIENT_ID" ] || [ -z "$SUBCONTEXT_CLIENT_SECRET" ]; then
  echo "Set SUBCONTEXT_CLIENT_ID and SUBCONTEXT_CLIENT_SECRET first (see the comment at the top of this file)." >&2
  exit 1
fi

# --data-urlencode keeps any unusual characters in the secret safe.
# resource says what the token is for (the Subcontext API). It is required.
curl --silent --show-error \
  --request POST "$base_url/oauth/token" \
  --header "Accept: application/json" \
  --data-urlencode "grant_type=client_credentials" \
  --data-urlencode "client_id=$SUBCONTEXT_CLIENT_ID" \
  --data-urlencode "client_secret=$SUBCONTEXT_CLIENT_SECRET" \
  --data-urlencode "scope=$scope" \
  --data-urlencode "resource=$base_url/api/v1" \
  --write-out "\n(HTTP status %{http_code})\n"
