#!/bin/sh
# fetch-auth0-token.sh -- Auth0 M2M token fetcher for Google WIF
#
# Called by the Google Auth library when using executable-sourced
# credentials (see google-wif-config.json).  Reads Auth0 client
# credentials from Docker secrets and returns the JWT in the format
# expected by Google's credential helpers.
#
# Exit codes:
#   0 -- success (JSON with token on stdout)
#   1 -- missing secrets or curl/jq failure

set -e

CLIENT_ID_FILE="/run/secrets/auth0-ocr-client-id"
CLIENT_SECRET_FILE="/run/secrets/auth0-ocr-client-secret"
AUTH0_DOMAIN="motovaultpro.us.auth0.com"
AUDIENCE="https://iam.googleapis.com/projects/487954699429/locations/global/workloadIdentityPools/motovaultpro-pool/providers/auth0-provider"

# Read credentials from Docker secrets
if [ ! -f "$CLIENT_ID_FILE" ]; then
  echo "Error: $CLIENT_ID_FILE not found" >&2
  exit 1
fi
if [ ! -f "$CLIENT_SECRET_FILE" ]; then
  echo "Error: $CLIENT_SECRET_FILE not found" >&2
  exit 1
fi

CLIENT_ID=$(cat "$CLIENT_ID_FILE" | tr -d '[:space:]')
CLIENT_SECRET=$(cat "$CLIENT_SECRET_FILE" | tr -d '[:space:]')

# Request M2M token from Auth0
# Write body to temp file, capture HTTP status code separately.
# Avoids --fail-with-body + set -e which swallows errors inside $().
BODY_FILE=$(mktemp)
HTTP_CODE=$(curl -s -w '%{http_code}' -o "$BODY_FILE" \
  --request POST \
  --url "https://${AUTH0_DOMAIN}/oauth/token" \
  --header 'Content-Type: application/json' \
  --data "{
    \"client_id\": \"${CLIENT_ID}\",
    \"client_secret\": \"${CLIENT_SECRET}\",
    \"audience\": \"${AUDIENCE}\",
    \"grant_type\": \"client_credentials\"
  }") || true
RESPONSE=$(cat "$BODY_FILE")
rm -f "$BODY_FILE"

if [ "$HTTP_CODE" != "200" ]; then
  echo "Error: Auth0 token request failed (HTTP $HTTP_CODE)" >&2
  echo "Response: $RESPONSE" >&2
  exit 1
fi

# Extract the access token
TOKEN=$(echo "$RESPONSE" | jq -r '.access_token')

if [ -z "$TOKEN" ] || [ "$TOKEN" = "null" ]; then
  echo "Error: No access_token in Auth0 response" >&2
  echo "$RESPONSE" >&2
  exit 1
fi

EXPIRY=$(echo "$RESPONSE" | jq -r '.expires_in')

# Calculate expiration timestamp (seconds since epoch)
EXPIRATION_TIME=$(($(date +%s) + ${EXPIRY:-3600}))

# Output in Google executable-sourced credential format
# https://cloud.google.com/iam/docs/workload-identity-federation-with-other-providers#create_a_credential_configuration
cat <<GCPEOF
{
  "version": 1,
  "success": true,
  "token_type": "urn:ietf:params:oauth:token-type:jwt",
  "id_token": "${TOKEN}",
  "expiration_time": ${EXPIRATION_TIME}
}
GCPEOF
