#!/bin/bash

# Define constants
TENANT_ID="945c199a-83a2-4e80-9f8c-5a91be5752dd"
CLIENT_ID="b151947c-b514-4997-a369-a9b76f26b050"
CLIENT_SECRET="tk_8Q~QYTj1FQYN2chWovu.M5Ph3YnIVzLwRJcoZ"
USERNAME="x.x@dell.com"
RESOURCE="https://graph.microsoft.com/"


urlencode() {
  local string="${1}"
  local strlen=${#string}
  local encoded=""
  local pos c o

  for (( pos=0 ; pos<strlen ; pos++ )); do
     c=${string:$pos:1}
     case "$c" in
        [-_.~a-zA-Z0-9] ) o="${c}" ;;
        * )               printf -v o '%%%02x' "'$c"
     esac
     encoded+="${o}"
  done
  echo "${encoded}"
}

# Prompt for password
read -sp "Enter password: " PASSWORD
echo ""

# Encode special characters in password
encoded_password=$(urlencode "$PASSWORD")

# Use curl to get access token

response=$(curl -X POST \
  https://login.microsoftonline.com/$TENANT_ID/oauth2/token \
  -H 'Content-Type: application/x-www-form-urlencoded' \
  -d "grant_type=password&client_id=$CLIENT_ID&client_secret=$CLIENT_SECRET&username=$USERNAME&password=$encoded_password&resource=$RESOURCE")

# Check if the request was successful
if [ $? -eq 0 ]; then
  # Extract access token from response
  access_token=$(echo "$response" | jq -r '.access_token')
  echo "Access token: $access_token"
else
  echo "Failed to obtain access token"
  echo "Response: $response"
fi
