#!/bin/bash

# Function to display usage
usage() {
  echo "Usage: $0 -c <client_id> -s <client_secret> -u <token_url> [-o <scope>] [-g <grant_type>]"
  exit 1
}

# Parse command line arguments
while getopts ":c:s:u:o:g:" opt; do
  case $opt in
    c) CLIENT_ID="$OPTARG"
    ;;
    s) CLIENT_SECRET="$OPTARG"
    ;;
    u) TOKEN_URL="$OPTARG"
    ;;
    o) SCOPE="$OPTARG"
    ;;
    g) GRANT_TYPE="$OPTARG"
    ;;
    \?) echo "Invalid option -$OPTARG" >&2
        usage
    ;;
  esac
done

# Check required parameters
if [ -z "$CLIENT_ID" ] || [ -z "$CLIENT_SECRET" ] || [ -z "$TOKEN_URL" ]; then
  usage
fi

# Set default values for optional parameters
if [ -z "$GRANT_TYPE" ]; then
  GRANT_TYPE="client_credentials"
fi

# Prepare the request body
REQUEST_BODY="grant_type=${GRANT_TYPE}&client_id=${CLIENT_ID}&client_secret=${CLIENT_SECRET}"
if [ -n "$SCOPE" ]; then
  REQUEST_BODY="${REQUEST_BODY}&scope=${SCOPE// /%20}"
fi

echo "curl -s -X POST $TOKEN_URL   -H Content-Type: application/x-www-form-urlencoded  -d $REQUEST_BODY"

# Get the OAuth2 token
response=$(curl -s -X POST "$TOKEN_URL" \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "$REQUEST_BODY")

# Extract the access token from the response
access_token=$(echo "$response" | jq -r .access_token)

# Check if the token was successfully obtained
if [ "$access_token" == "null" ]; then
  echo "Failed to obtain access token"
  echo "Response: $response"
  exit 1
fi

# Output the access token
echo "GTOKEN = $access_token"
# Export the access token as an environment variable
export "GTOKEN=$access_token"
