#!/bin/sh

# Authentification Oauth2 en flow client_credentials
#
# Usage :
#   oauth2_token.sh [CLIENT_ID] [CLIENT_SECRET] [URL_TOKEN]
#   oauth2_token.sh [PROFIL]
#
# Le script est essentiellement un emballage sur une simple requête curl :
# curl -d "grant_type=client_credentials" -u "CLIENT_ID:CLIENT_SECRET" URL_TOKEN

err() {
  echo $1 >&2
}

usage() {
  echo "Usage :"
  echo "  $(basename $0) [CLIENT_ID] [CLIENT_SECRET] [URL_TOKEN]"
  echo "  $(basename $0) [PROFIL]"
}

# Récupération des informations d'authentification
CONFIG_DIR=$HOME/.config/o2token
if [ $# -eq 1 ]; then
  # En fichier de profil
  [ -f "$1" ] && . $1
  [ -f "$CONFIG_DIR/$1.o2rc" ] && . "$CONFIG_DIR/$1.o2rc"
  [ -z "$O2_CLIENT_ID" ] && err "Configuration incorrecte : $1" && exit 1
else
  # En ligne de commande
  if [ $# -ge 3 ]; then
    O2_CLIENT_ID=$1
    O2_CLIENT_SECRET=$2
    O2_URL_TOKEN=$3
  else
    usage && exit 1
  fi
fi

# Capture de la réponse Json
O2_TOKEN_JSON=$(curl -s -S $O2_URL_TOKEN \
  -d "grant_type=client_credentials" \
  -u "$O2_CLIENT_ID:$O2_CLIENT_SECRET" \
  )
[ -z "$O2_TOKEN_JSON" ] && err "Erreur d'authentification" && exit 2

# Extraction du token, code error si inexistant (-e)
O2_TOKEN=$(echo $O2_TOKEN_JSON | jq -re .access_token)

# Restitution
if [ $? -eq 0 ]; then
 echo "$O2_TOKEN"
else
  err "Echec d'authentification"
  err "$O2_TOKEN_JSON"
  exit 3
fi