#!/bin/sh
#Load Configuration Data
. ./config.txt

#Get test case name
testcase=$0

#Local parameter for this script
count=0
scope=myTestScope
resource_server_delete="$default_resource_server""/""$scope"

# Print test case detailed output to result_details file
echo "-------------------------------------$testcase:-------------------------------------------------- "  >> $result_details
echo "Test to register and deletion of scope. This test will create and then delete scope " >> $result_details
echo "username is: $scope_username " >> $result_details
echo "password is: $scope_password " >> $result_details
echo "Scope is: $scope_full " >> $result_details
echo "" >> $result_details

#Get the Access token
curl -v -k -X POST -d 'grant_type=password&client_id='"$client_id"'&client_secret='"$client_secret"'&username='"$scope_username"'&password='"$scope_password"'&scope='"$scope_full" "$grant_url"  -o curloutput

access_token=`cat curloutput | jq ".access_token" | cut -d\" -f2`
echo $access_token

echo "Access token is: $access_token" >> $result_details
echo "" >> $result_details

#List scope and find out scope name
curl -k -H "Content-Type: application/json" -H 'Authorization: Bearer '"$access_token" $default_resource_server  -o scope_list
scopes=`cat scope_list | jq "[.scopes]" | cut -d\" -f2`
echo "Scopes name is : $scopes" >> $result_details

#Register Scope available
curl -k -H "Content-Type: application/json" -H 'Authorization: Bearer '"$access_token"  -d '{"scope":"'$scope'","claims": ["name", "family_name", "given_name", "middle_name", "nickname", "preferred_username", "profile", "picture", "website", "gender", "birthdate", "zoneinfo", "locale", "updated_at"],"scope_description":"View profile scope"}' $default_resource_server > out_list

echo "Register scope is: " >> $result_details
cat out_list >> $result_details
echo "" >> $result_details

scope_name=`cat out_list | jq ".scope" | cut -d\" -f2`
echo "Scope Name is: $scope_name" >> $result_details

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

# Print test case is passed or failed
echo -n $testcase":" >> $result_summary
if [ "$scope_name" == "$scope" ]
then
        echo "PASSED" >>  $result_summary
else
        echo "FAILED" >>  $result_summary
fi

#delete the created scope
curl -k -H "Content-Type: application/json" -H 'Authorization: Bearer '"$access_token" -X DELETE "$resource_server_delete"

#Remove all temporary files used by this script
rm curloutput scope_list out_list c
