#!/bin/sh
#Input Parameter File Name.

. ./config.txt

testcase=$0
device_id="Authflow_sles12Test"

# Login using credentials
curl -v -b c -c c -k -X POST -d 'option=credential&Ecom_User_ID='"$username"'&Ecom_Password='"$password" "$loginurl" -L

# Request for authorization code
curl -v -b c -c c -k "$authcodeurl"'?response_type=code&client_id='"$client_id"'&client_secret='"$client_secret"'&redirect_uri='"$redirect_uri" -L > temp 2>&1

#Retrieve Authorization Code from previous output
authzcode=`grep code= temp | awk -F: '{print $1}'| awk -F? '{print $2}' | awk -F= '{print $2}' | cut -d' ' -f1` 
authzcode=`echo $authzcode | sed -e 's/ *$//g'`
# Print test case detailed output to result_details file
echo "-------------------------------------$testcase:-------------------------------------------------- "  >> $result_details
echo "Authflow: Revoke all token using device ID at global level - with device ID" >> $result_details
echo "" >> $result_details
echo "client id is: $client_id " >> $result_details
echo "client secret is: $client_secret" >> $result_details
echo "redirect uri used in code is: $redirect_uri" >> $result_details
echo "" >> $result_details
echo "auth code is: $authzcode " >> $result_details
echo "" >> $result_details

#get token
curl -v -b c -c c -k -L -d 'grant_type=authorization_code&client_id='"$client_id"'&client_secret='"$client_secret"'&redirect_uri='"$redirect_uri"'&device_id='"$device_id"'&code='"${authzcode}" "$grant_url" -o curloutput

token_access=`cat curloutput | jq ".access_token" | cut -d\" -f2`
token_type=`cat curloutput | jq ".token_type" | cut -d\" -f2`
expires_in=`cat curloutput | jq ".expires_in" | cut -d\" -f2`
refresh_token=`cat curloutput | jq ".refresh_token" | cut -d\" -f2`
echo " Token output is : $token_access " >> $result_details

#Revoke token
#curl -v -k -X POST -d 'client_id='"$client_id"'&client_secret='"$client_secret"'&token='"$refresh_token" "$revokeEP"

curl -v -k -H "Content-Type: application/x-www-form-urlencoded" -X POST -d 'userstore_name='"$userstore"'&user_dn='"$user_dn" "$revokeEP""/"$device_id


#send revoked refresh token to  get access token
curl -v -k -X POST -d 'grant_type=refresh_token&client_id='"$client_id"'&client_secret='"$client_secret"'&refresh_token='"$refresh_token" "$grant_url" -o token_output

error=`cat token_output | jq ".error" | cut -d\" -f2`
error_des=`cat token_output | jq ".error_description" | cut -d\" -f2`

echo "-------------------------------------------------------------------------------------------------------"  >> $result_details

# Print test case is passed or failed
echo -n $testcase":" >> $result_summary
if [ "$token_access" != "" ] && [ "$error" == "invalid_grant" ] && [ "$error_des" == "invalid_grant: Refresh token has been revoked." ]
then
	echo "PASSED" >>  $result_summary
else
	echo "FAILED" >>  $result_summary
fi


#Remove all temporary files used by this script
rm temp
rm curloutput
rm c
#rm token_output
