C Common Helper Functions for cURL

#!/bin/sh

SERVER_URL="http://SERVER:PORT"
USERNAME="epm_default_cloud_admin"
PASSWORD="epm_cloud"
APP_NAME="Vision"
API_VERSION="11.1.2.3.600"

funcRemoveTempFiles() {
	for var in "$@"
	do
		if [ -f $var ]; then
			rm $var
		fi
	done
}

funcPrintErrorDetails() {
	contentType=`echo $(grep 'Content-Type:' respHeader.txt) | tr -d [:space:]`
	if [ ! -z $contentType ] && [[ $contentType = *"application/json"* ]]; then
		output=`cat $1`
		error=`echo $output | jq '.details'`
		echo "Error details: " $error
	fi
}

funcExecuteRequest() {
	if [ ! -z "$4" ]; then
		statusCode=`curl -X $1 -s -w "%{http_code}" -u "$USERNAME:$PASSWORD" -o "response.txt" -D "respHeader.txt" -H "Content-Type: $4" -d $3 $2`
	else
		statusCode=`curl -X $1 -s -w "%{http_code}" -u "$USERNAME:$PASSWORD" -o "response.txt" -D "respHeader.txt" -H "Content-Type: $3" $2`
	fi
	if [ $statusCode != 200 ]; then
		echo "Error executing request"
		if [ $statusCode != 000 ]; then
			echo "Response error code : " $statusCode
			funcPrintErrorDetails "response.txt"
			funcRemoveTempFiles "respHeader.txt" "response.txt"
		fi
		exit 0
	fi
}

funcGetStatus() {
	output=`cat response.txt`
	count=`echo $output | jq '.links | length'`
	i=0
	pingUrl=""
	while [ $i -lt $count ]; do
		rel=`echo $output | jq '.links['$i'].rel'`
		rel=`echo "$rel" | tr -d "\""`
		if [ "$rel" == "Job Status" ]; then
				pingUrl=`echo $output | jq '.links['$i'].href'`
				pingUrl=`echo "$pingUrl" | tr -d "\""`
		fi
		i=`expr $i + 1`
	done
	echo $pingUrl
	completed="false"
	while [ $completed != "true" ]; do
		statusCode2=`curl -X $1 -s -w "%{http_code}" -u "$USERNAME:$PASSWORD" -o "pingResponse.txt"  -H "Content-Type: application/x-www-form-urlencoded" "$pingUrl"`
		if [ $statusCode2 == 200 ]; then
			status2=`jq '.status' pingResponse.txt`
			if [ $status2 != -1 ]; then
				completed="true"
				echo "Job completed"
			else
				echo "Please wait..."
				sleep 20
			fi
			
		else
			echo "Please wait..."
			sleep 20
		fi
		funcRemoveTempFiles "pingResponse.txt"
	done
}

funcGetMigrationStatus() {
	output=`cat response.txt`
	count=`echo $output | jq '.links | length'`
	i=0
	pingUrl=""
	while [ $i -lt $count ]; do
		rel=`echo $output | jq '.links['$i'].rel'`
		rel=`echo "$rel" | tr -d "\""`
		if [ "$rel" == "Job Status" ]; then
				pingUrl=`echo $output | jq '.links['$i'].href'`
				pingUrl=`echo "$pingUrl" | tr -d "\""`
		fi
		i=`expr $i + 1`
	done
	echo $pingUrl
	completed="false"
	while [ $completed != "true" ]; do
		statusCode2=`curl -X $1 -s -w "%{http_code}" -u "$USERNAME:$PASSWORD" -o "pingResponse.txt"  -H "Content-Type: application/x-www-form-urlencoded" "$pingUrl"`
		if [ $statusCode2 == 200 ]; then
			status2=`jq '.status' pingResponse.txt`
			if [ $status2 == 0 ]; then
				completed="true"
				echo "Job completed"
			elif [ $status2 == 1 ]; then
				output1=`cat pingResponse.txt`
				echo "Error occurred"
				count=`echo $output1 | jq '.items | length'`
				if [ $count == 0 ]; then
					echo `echo $output1 | jq '.details'`
				else 
					i=0
					while [ $i -lt $count ]; do
						echo "Source : " `echo $output1 | jq '.items['$i'].source'`
						echo "Destination :" `echo $output1 | jq '.items['$i'].destination'`
						firstPing=`echo $output1 | jq '.items['$i'].links[0].href'`
						echo ""
						taskCompleted="false"
						while [ $taskCompleted != "true" ]; do
							statusCode3=`curl -X "GET" -s -w "%{http_code}" -u "$USERNAME:$PASSWORD" -o "taskpingResponse.txt"  -H "Content-Type: application/x-www-form-urlencoded" "$firstPing"`
							echo $statusCode3
							output2=`cat taskpingResponse.txt`
							count1=`echo $output2 | jq '.items | length'`
							j=0
							currentMessageCategory=""
							while [ $j -lt $count1 ]; do
								msgCategory=`echo $output1 | jq '.items['$i'].msgCategory'`
								if [ !-z $currentMessageCategory ] || [ $currentMessageCategory != $msgCategory ]; then
									currentMessageCategory=msgCategory
									echo $currentMessageCategory
								fi
								echo `echo $output2 | jq '.items['$i'].artifact'` " - " `echo $output2 | jq '.items['$i'].msgText'`
								count2=`echo $output | jq '.links | length'`
								k=0
								firstPing=""
								while [ $k -lt $count ]; do
									rel=`echo $output2 | jq '.links['$i'].rel'`
									rel=`echo "$rel" | tr -d "\""`
									if [ "$rel" == "next" ]; then
											firstPing=`echo $output2 | jq '.links['$i'].href'`
											firstPing=`echo "$firstPing" | tr -d "\""`
									fi
									k=`expr $k + 1`
								done
								if [ -z $firstPing ]; then
									taskCompleted="true"
								fi
								j=`expr $j + 1`
							done
						done
						i=`expr $i + 1`
					done
				fi
			else
				echo "Please wait..."
				sleep 20
			fi
			
		else
			echo "Please wait..."
			sleep 20
		fi
		funcRemoveTempFiles "pingResponse.txt" "taskpingResponse.txt"
	done
}	
		

funcGetLCMVersions() {
	url=$SERVER_URL/interop/rest
	funcExecuteRequest "GET" $url "application/x-www-form-urlencoded"

	output=`cat response.txt`
	status=`echo $output | jq '.status'`
	if [ $status == 0 ]; then
		echo "List of versions :"
		count=`echo $output | jq '.items | length'`
		i=0
		while [ $i -lt $count ]; do
			echo "Version : " `echo $output | jq '.items['$i'].version'`
			echo "Lifecycle :" `echo $output | jq '.items['$i'].lifecycle'`
			echo "Latest :" `echo $output | jq '.items['$i'].latest'`
			echo "Link :" `echo $output | jq '.items['$i'].links[0].href'`
			echo ""
			i=`expr $i + 1`
		done
	else
		error=`echo $output | jq '.details'`
		echo "Error occurred. " $error
	fi
	funcRemoveTempFiles "respHeader.txt" "response.txt"
}

funcGetLCMVersionDetails() {
	url=$SERVER_URL/interop/rest/$API_VERSION
	funcExecuteRequest "GET" $url "application/x-www-form-urlencoded"

	output=`cat response.txt`
	status=`echo $output | jq '.status'`
	if [ $status == 0 ]; then
		echo "Version $API_VERSION details :"
		count=`echo $output | jq '.links | length'`
		i=0
		while [ $i -lt $count ]; do
			echo "Service : " `echo $output | jq '.links['$i'].rel'`
			echo "URL :" `echo $output | jq '.links['$i'].href'`
			echo "Action :" `echo $output | jq '.links['$i'].action'`
			echo ""
			i=`expr $i + 1`
		done
	else
		error=`echo $output | jq '.details'`
		echo "Error occurred. " $error
	fi
	funcRemoveTempFiles "respHeader.txt" "response.txt"
}

funcGetServices() {
	url=$SERVER_URL/interop/rest/$API_VERSION/services
	funcExecuteRequest "GET" $url "application/x-www-form-urlencoded"

	output=`cat response.txt`
	status=`echo $output | jq '.status'`
	if [ $status == 0 ]; then
		echo "Services list :"
		count=`echo $output | jq '.links | length'`
		i=0
		while [ $i -lt $count ]; do
			rel=`echo $output | jq '.links['$i'].rel'`
			rel=`echo "$rel" | tr -d "\""`
			if [ "$rel" != "self" ]; then
				echo "Service : " `echo $output | jq '.links['$i'].rel'`
				echo "URL :" `echo $output | jq '.links['$i'].href'`
				echo "Action :" `echo $output | jq '.links['$i'].action'`
				echo ""
			fi
			i=`expr $i + 1`
		done
	else
		error=`echo $output | jq '.details'`
		echo "Error occurred. " $error
	fi
	funcRemoveTempFiles "respHeader.txt" "response.txt"
}

funcRecreateService() {
	echo "Are you sure you want to recreate the EPM environment (yes/no): no ?[Press Enter]"
	read toCreate
	if [ $toCreate != "yes" ]; then
		echo "User cancelled the recreate command"
		exit 0
	fi
	
	url=$SERVER_URL/interop/rest/$API_VERSION/services/$1/recreate
	funcExecuteRequest "POST" $url "application/x-www-form-urlencoded"

	output=`cat response.txt`
	status=`echo $output | jq '.status'`
    if [ $status == -1 ]; then
        echo "Started recreating the environment successfully"
		funcGetStatus "GET"
    else
        error=`echo $output | jq '.details'`
        echo "Error occurred. " $error
    fi
	funcRemoveTempFiles "respHeader.txt" "response.txt"
}

funcGetApplicationSnapshotDetails() {
	encodedFileName=$(echo $1 | sed -f urlencode.sed)
	url=$SERVER_URL/interop/rest/$API_VERSION/applicationsnapshots/$encodedFileName
	funcExecuteRequest "GET" $url "application/x-www-form-urlencoded"

	output=`cat response.txt`
	status=`echo $output | jq '.status'`
	if [ $status == 0 ]; then
		echo "Application details :"
		echo "Application snapshot name : " `echo $output | jq '.items[0].name'`
		echo "Application snapshot type : " `echo $output | jq '.items[0].type'`
		echo "Can be exported flag : " `echo $output | jq '.items[0].canExport'`
		echo "Can be imported flag : " `echo $output | jq '.items[0].canImport'`
		echo "Can be uploaded flag : " `echo $output | jq '.items[0].canUpload'`
		echo "Can be downloaded flag : " `echo $output | jq '.items[0].canDownload'`
		count=`echo $output | jq '.links | length'`
		i=0
		echo "Services details :"
		while [ $i -lt $count ]; do
			echo "Service : " `echo $output | jq '.links['$i'].rel'`
			echo "URL :" `echo $output | jq '.links['$i'].href'`
			echo "Action :" `echo $output | jq '.links['$i'].action'`
			echo ""
			i=`expr $i + 1`
		done
	else
		error=`echo $output | jq '.details'`
		echo "Error occurred. " $error
	fi
	funcRemoveTempFiles "respHeader.txt" "response.txt"
}

funcListFiles() {
	url=$SERVER_URL/interop/rest/$API_VERSION/applicationsnapshots
	funcExecuteRequest "GET" $url "application/x-www-form-urlencoded"

	list=`cat response.txt | jq 'select(.items != null) | .items[].name'`
	if [[ ! -z $list ]]; then
		echo $list
	else
		echo "No files found"
	fi
	funcRemoveTempFiles "respHeader.txt" "response.txt"
}


funcDeleteFile() {
	encodedFileName=$(echo $1 | sed -f urlencode.sed)
	url=$SERVER_URL/interop/rest/$API_VERSION/applicationsnapshots/$encodedFileName
	funcExecuteRequest "DELETE" $url "application/x-www-form-urlencoded"

	output=`cat response.txt`
	status=`echo $output | jq '.status'`
    if [ $status == 0 ]; then
        echo "Deleted successfully"
    else
        error=`echo $output | jq '.details'`
        echo "Error occurred. " $error
    fi
	funcRemoveTempFiles "respHeader.txt" "response.txt"
}

funcUploadFile() {
	infile=$1
	if [ ! -f $infile ]; then
		echo "File does not exist"
		exit 0
	fi
	encodedFileName=$(echo $infile | sed -f urlencode.sed)
	url="$SERVER_URL/interop/rest/$API_VERSION/applicationsnapshots/$encodedFileName/contents?q="
	filename=$( basename $infile)
	filesize=$( stat -c %s $infile)
	bs=52428800
	noOfPackets=$(($((filesize / bs)) + 1))
	uploadedsize=0
	isFirst=true
	count=1
	isLast="false"
	if [ $noOfPackets = 1 ]; then
	  isLast="true"
	fi
	tempFile=/u01/temp/$filename

	if [ ! -d "/u01/temp" ]; then
		mkdir /u01/temp
	fi

	while [ $uploadedsize -ne $filesize ]
	do
		skip=$uploadedsize
		temp=$((filesize - uploadedsize))
		if [ $temp -le $bs ]; then
			length=$temp
		else
			length=$bs
		fi
		echo "Skip : $skip"
		echo "Length : $length"
		
		(
			dd bs=1 skip=$skip count=0 &> /dev/null
			dd bs=$length count=1 of=$tempFile &> /dev/null
		) < "$infile"
		
		param=$(echo "{chunkSize=$length,isFirst=$isFirst,isLast=$isLast}" | sed -f urlencode.sed)
		urlwithparam="$url$param"
		echo $urlwithparam
		statusCode=`curl -X POST -s -w "%{http_code}" -T $tempFile -u "$USERNAME:$PASSWORD" -o "response.txt" -D "respHeader.txt" -H "Content-Type: application/octet-stream" "$urlwithparam"`

		funcRemoveTempFiles $tempFile

		if [ $statusCode == 200 ]; then
			output=`cat response.txt`
			status=`echo $output | jq '.status'`
			if [ $status -gt 0 ]; then
				error=`echo $output | jq '.details'`
				echo "Error occurred. " $error
				funcRemoveTempFiles "respHeader.txt" "response.txt"
				exit 0
			else if [ $status == -1 ] || [ $isLast == "true" ]; then
					funcGetStatus "GET"
				fi
			fi
		else
			echo "Error executing request"
			if [ $statusCode != 000 ]; then
				echo "Response error code : " $statusCode
				funcPrintErrorDetails "response.txt"
				funcRemoveTempFiles "respHeader.txt" "response.txt"
			fi
			exit 0
		fi
		funcRemoveTempFiles "respHeader.txt" "response.txt"
		uploadedsize=$((uploadedsize + length))
		isFirst="false"
		echo "isFirst : $isFirst"
		count=$((count + 1))
		if [ $count = $noOfPackets ]; then
			isLast="true"
		fi
		echo "Uploaded Size : $uploadedsize"
		echo "isLast : $isLast"
	done

	echo "Uploaded File Successfully"
}

funcDownloadFile() {
	filepath="/u01/$1"
	encodedFileName=$(echo $1 | sed -f urlencode.sed)
	url=$SERVER_URL/interop/rest/$API_VERSION/applicationsnapshots/$encodedFileName/contents
	statusCode=`curl -X GET -s -w "%{http_code}" -u "$USERNAME:$PASSWORD" -o $filepath -H "Content-Type: application/x-www-form-urlencoded" -D respHeader.txt $url`

	if [ $statusCode == 200 ]; then
		contentType=`echo $(grep 'Content-Type:' respHeader.txt) | tr -d [:space:]`
		if [ ! -z $contentType ] && [[ $contentType = *"application/json"* ]]; then
			output=`cat $filepath`
			error=`echo $output | jq '.details'`
			echo "Error occurred. " $error
			funcRemoveTempFiles $filepath
		else
			fileExtension=`echo $(grep -r "fileExtension: " respHeader.txt | awk  '{print ($2)}') | tr -d [:space:]`
			if [ ! -z $fileExtension ]; then
				if [[ ! $filepath =~ \.$fileExtension$ ]]; then
					mv $filepath $filepath.$fileExtension
				fi
			fi
			echo "Downloaded file successfully"
		fi
	else
		echo "Error listing files. "
		if [ $statusCode != 000 ]; then
			echo "Response error code : " $statusCode
			funcPrintErrorDetails $filepath
			funcRemoveTempFiles $filepath
		fi
	fi
	funcRemoveTempFiles "respHeader.txt"
}

funcImportSnapshot() {
	param=$(echo "{type:import}" | sed -f urlencode.sed)
	encodedFileName=$(echo $1 | sed -f urlencode.sed)
	url=$SERVER_URL/interop/rest/$API_VERSION/applicationsnapshots/$encodedFileName/migration?q=$param
	funcExecuteRequest "POST" $url "application/x-www-form-urlencoded"

	output=`cat response.txt`
	status=`echo $output | jq '.status'`
    if [ $status == -1 ]; then
        echo "Started importing successfully"
		funcGetMigrationStatus "POST"
    else
        error=`echo $output | jq '.details'`
        echo "Error occurred. " $error
    fi
	funcRemoveTempFiles "respHeader.txt" "response.txt"
}

funcExportSnapshot() {
	param=$(echo "{type:export}" | sed -f urlencode.sed)
	encodedFileName=$(echo $1 | sed -f urlencode.sed)
	url=$SERVER_URL/interop/rest/$API_VERSION/applicationsnapshots/$encodedFileName/migration?q=$param
	funcExecuteRequest "POST" $url "application/x-www-form-urlencoded"

	output=`cat response.txt`
	status=`echo $output | jq '.status'`
    if [ $status == -1 ]; then
        echo "Started exporting succesfully"
		funcGetMigrationStatus "POST"
    else
        error=`echo $output | jq '.details'`
        echo "Error occurred. " $error
    fi
	funcRemoveTempFiles "respHeader.txt" "response.txt"
}

funcProvideFeedback() {
	url=$SERVER_URL/interop/rest/$LCM_VERSION/feedback
	description=$(echo $1 | sed -f urlencode.sed)
	param="{\"configuration\":{\"URL\":\"$SERVER_URL\"},\"description\":\"$description\"}"
	funcExecuteRequest "POST" $url $param "application/json"

	output=`cat response.txt`
	status=`echo $output | jq '.status'`
	if [ $status == 0 ]; then
		echo "Feedback successful"
    else
        error=`echo $output | jq '.details'`
        echo "Error occurred. " $error
    fi
	funcRemoveTempFiles "respHeader.txt" "response.txt"
}

funcHardReset() {
	echo "Are you sure you want to restart the service instance (yes/no): no ?[Press Enter] "
	read toCreate
	if [ $toCreate != "yes" ]; then
		echo "User cancelled the recreate command"
		exit 0
	fi
	
	url=$SERVER_URL/interop/rest/$LCM_VERSION/services/PBCS/resetservice
	comment=$(echo $1 | sed -f urlencode.sed)
	param="{\"comment\":\"$comment\"}"
	funcExecuteRequest "POST" $url $param "application/json"

	output=`cat response.txt`
	status=`echo $output | jq '.status'`
    if [ $status == -1 ]; then
        echo "Started hard reset succesfully"
		funcGetStatus "GET"
    else
        error=`echo $output | jq '.details'`
        echo "Error occurred. " $error
    fi
	funcRemoveTempFiles "respHeader.txt" "response.txt"
}

funcGenerateAuditReport(){
	param=$(echo "{type:userauditreport,fileName:$1,since:$2,until:$3}" | sed -f urlencode.sed)
	url=$SERVER_URL/interop/rest/$API_VERSION/reports?q=$param
	funcExecuteRequest "POST" $url "application/x-www-form-urlencoded"

	output=`cat response.txt`
	status=`echo $output | jq '.status'`
    if [ $status == -1 ]; then
        echo "Started generating report successfully"
		funcGetStatus "GET"
    else
        error=`echo $output | jq '.details'`
        echo "Error occurred. " $error
    fi
	funcRemoveTempFiles "respHeader.txt" "response.txt"
}

funcGenerateProvisionReport(){
	param=$(echo "{type:provisionreport,fileName:$1}" | sed -f urlencode.sed)
	url=$SERVER_URL/interop/rest/$API_VERSION/reports?q=$param
	funcExecuteRequest "POST" $url "application/x-www-form-urlencoded"

	output=`cat response.txt`
	status=`echo $output | jq '.status'`
    if [ $status == -1 ]; then
        echo "Started generating report successfully"
		funcGetStatus "GET"
    else
        error=`echo $output | jq '.details'`
        echo "Error occurred. " $error
    fi
	funcRemoveTempFiles "respHeader.txt" "response.txt"
}


funcExecuteJob() {
	url="$SERVER_URL/HyperionPlanning/rest/$API_VERSION/applications/$APP_NAME/jobs"
	encodedJobName=$(echo $2 | sed -f urlencode.sed)
	if [ ! -z "$3" ]; then
		param="jobType=$1&jobName=$encodedJobName&parameters=$3"
	else
		param="jobType=$1&jobName=$encodedJobName"
	fi
	funcExecuteRequest "POST" $url $param "application/json"

	output=`cat response.txt`
	status=`echo $output | jq '.status'`
    if [ $status == -1 ]; then
        echo "Started executing job successfully"
		funcGetStatus "GET"
    else
        error=`echo $output | jq '.details'`
        echo "Error occurred. " $error
    fi
	funcRemoveTempFiles "respHeader.txt" "response.txt"
}

funcIntegrationScenarioImportMetadataIntoApplication() {
	funcUploadFile "DemoApplication_HSS_Vision.zip"
	funcExecuteJob "IMPORT_METADATA" "accountMetadata" "{importZipFileName=accounts.zip}"
	funcExecuteJob "CUBE_REFRESH" "cubeRefresh"
}

funcIntegrationScenarioImportDataRunCalcCopyToAso() {
    funcUploadFile "data.csv"
    funcExecuteJob "IMPORT_DATA" "loadingq1data" "{importFileName=data.csv}"
    funcExecuteJob "CUBE_REFRESH","cubeRefresh"
    funcExecuteJob "PLAN_TYPE_MAP" "CampaignToReporting" "{clearData=false}"
}

funcIntegrationScenarioExportMetadataAndDataAndDownloadFiles() {
    funcExecuteJob "EXPORT_METADATA" "exportentitymetadata" "{exportZipFileName=entitydata.zip}"
    funcExecuteJob "EXPORT_DATA" "Forecastdata" "{exportFileName=forecastdata.zip}"
    funcListFiles      
    funcDownloadFile "entitydata.zip"
    funcDownloadFile "forecastdata.zip"
}

funcIntegrationScenarioRemoveUnnecessaryFiles() {
    funcListFiles
    funcDeleteFile "entitymetadata.csv"
    funcDeleteFile "forecastdata.csv"
}

funcIntegrationScenarioExportDataAndDownloadFiles() {
    funcExecuteJob "EXPORT_DATA" "entitydata" "{exportFileName:entitydata.zip}"
    funcExecuteJob "EXPORT_DATA" "forecastdata" "{exportFileName:forecastdata.zip}"
    funcListFiles
    funcDownloadFile "entitydata.zip"
    funcDownloadFile "forecastdata.zip"
}

funcIntegrationScenarioRefreshTheApplication() {
    funcUploadFile "accounts.zip"
    funcExecuteJob "IMPORT_METADATA" "accountMetadata" "{importZipFileName:accounts.zip}"
    funcExecuteJob "CUBE_REFRESH" "cubeRefresh"
}

funcIntegrationScenarioCloneServiceInstance() {
	# Part 1 : Change SERVER_URL, USERNAME, PASSWORD, API_VERSION variables values to match those of first environment
	# Download file from source instance. 
	# Comment out all lines below Part 2
	# Uncomment the below line for the first step.
	# funcDownloadFile "Artifact Snapshot" 
	
	# Part 2 : Change SERVER_URL, USERNAME, PASSWORD, API_VERSION to match those of second environment.
	# Clone the service instance. 
	# Comment out code for download file.
	# Uncomment below lines
	funcRecreateService "PBCS"
	funcDeleteFile "Artifact Snapshot"
    funcUploadFile "Artifact Snapshot.zip"
	funcImportSnapshot "Artifact Snapshot"
}

funcIntegrationScenarioImportMetadataIntoApplication
funcIntegrationScenarioImportDataRunCalcCopyToAso
funcIntegrationScenarioExportMetadataAndDataAndDownloadFiles
funcIntegrationScenarioRemoveUnnecessaryFiles
funcIntegrationScenarioExportDataAndDownloadFiles
funcIntegrationScenarioRefreshTheApplication#!/bin/sh

SERVER_URL="http://SERVER:PORT"
USERNAME="epm_default_cloud_admin"
PASSWORD="epm_cloud"
APP_NAME="Vision"
API_VERSION="11.1.2.3.600"

funcRemoveTempFiles() {
	for var in "$@"
	do
		if [ -f $var ]; then
			rm $var
		fi
	done
}

funcPrintErrorDetails() {
	contentType=`echo $(grep 'Content-Type:' respHeader.txt) | tr -d [:space:]`
	if [ ! -z $contentType ] && [[ $contentType = *"application/json"* ]]; then
		output=`cat $1`
		error=`echo $output | jq '.details'`
		echo "Error details: " $error
	fi
}

funcExecuteRequest() {
	if [ ! -z "$4" ]; then
		statusCode=`curl -X $1 -s -w "%{http_code}" -u "$USERNAME:$PASSWORD" -o "response.txt" -D "respHeader.txt" -H "Content-Type: $4" -d $3 $2`
	else
		statusCode=`curl -X $1 -s -w "%{http_code}" -u "$USERNAME:$PASSWORD" -o "response.txt" -D "respHeader.txt" -H "Content-Type: $3" $2`
	fi
	if [ $statusCode != 200 ]; then
		echo "Error executing request"
		if [ $statusCode != 000 ]; then
			echo "Response error code : " $statusCode
			funcPrintErrorDetails "response.txt"
			funcRemoveTempFiles "respHeader.txt" "response.txt"
		fi
		exit 0
	fi
}

funcGetStatus() {
	output=`cat response.txt`
	count=`echo $output | jq '.links | length'`
	i=0
	pingUrl=""
	while [ $i -lt $count ]; do
		rel=`echo $output | jq '.links['$i'].rel'`
		rel=`echo "$rel" | tr -d "\""`
		if [ "$rel" == "Job Status" ]; then
				pingUrl=`echo $output | jq '.links['$i'].href'`
				pingUrl=`echo "$pingUrl" | tr -d "\""`
		fi
		i=`expr $i + 1`
	done
	echo $pingUrl
	completed="false"
	while [ $completed != "true" ]; do
		statusCode2=`curl -X $1 -s -w "%{http_code}" -u "$USERNAME:$PASSWORD" -o "pingResponse.txt"  -H "Content-Type: application/x-www-form-urlencoded" "$pingUrl"`
		if [ $statusCode2 == 200 ]; then
			status2=`jq '.status' pingResponse.txt`
			if [ $status2 != -1 ]; then
				completed="true"
				echo "Job completed"
			else
				echo "Please wait..."
				sleep 20
			fi
			
		else
			echo "Please wait..."
			sleep 20
		fi
		funcRemoveTempFiles "pingResponse.txt"
	done
}

funcGetLCMVersions() {
	url=$SERVER_URL/interop/rest
	funcExecuteRequest "GET" $url "application/x-www-form-urlencoded"

	output=`cat response.txt`
	status=`echo $output | jq '.status'`
	if [ $status == 0 ]; then
		echo "List of versions :"
		count=`echo $output | jq '.items | length'`
		i=0
		while [ $i -lt $count ]; do
			echo "Version : " `echo $output | jq '.items['$i'].version'`
			echo "Lifecycle :" `echo $output | jq '.items['$i'].lifecycle'`
			echo "Latest :" `echo $output | jq '.items['$i'].latest'`
			echo "Link :" `echo $output | jq '.items['$i'].links[0].href'`
			echo ""
			i=`expr $i + 1`
		done
	else
		error=`echo $output | jq '.details'`
		echo "Error occurred. " $error
	fi
	funcRemoveTempFiles "respHeader.txt" "response.txt"
}

funcGetLCMVersionDetails() {
	url=$SERVER_URL/interop/rest/$API_VERSION
	funcExecuteRequest "GET" $url "application/x-www-form-urlencoded"

	output=`cat response.txt`
	status=`echo $output | jq '.status'`
	if [ $status == 0 ]; then
		echo "Version $API_VERSION details :"
		count=`echo $output | jq '.links | length'`
		i=0
		while [ $i -lt $count ]; do
			echo "Service : " `echo $output | jq '.links['$i'].rel'`
			echo "URL :" `echo $output | jq '.links['$i'].href'`
			echo "Action :" `echo $output | jq '.links['$i'].action'`
			echo ""
			i=`expr $i + 1`
		done
	else
		error=`echo $output | jq '.details'`
		echo "Error occurred. " $error
	fi
	funcRemoveTempFiles "respHeader.txt" "response.txt"
}

funcGetServices() {
	url=$SERVER_URL/interop/rest/$API_VERSION/services
	funcExecuteRequest "GET" $url "application/x-www-form-urlencoded"

	output=`cat response.txt`
	status=`echo $output | jq '.status'`
	if [ $status == 0 ]; then
		echo "Services list :"
		count=`echo $output | jq '.links | length'`
		i=0
		while [ $i -lt $count ]; do
			rel=`echo $output | jq '.links['$i'].rel'`
			rel=`echo "$rel" | tr -d "\""`
			if [ "$rel" != "self" ]; then
				echo "Service : " `echo $output | jq '.links['$i'].rel'`
				echo "URL :" `echo $output | jq '.links['$i'].href'`
				echo "Action :" `echo $output | jq '.links['$i'].action'`
				echo ""
			fi
			i=`expr $i + 1`
		done
	else
		error=`echo $output | jq '.details'`
		echo "Error occurred. " $error
	fi
	funcRemoveTempFiles "respHeader.txt" "response.txt"
}

funcRecreateService() {
	echo "Are you sure you want to recreate the EPM environment (yes/no): no ?[Press Enter]"
	read toCreate
	if [ $toCreate != "yes" ]; then
		echo "User cancelled the recreate command"
		exit 0
	fi
	
	url=$SERVER_URL/interop/rest/$API_VERSION/services/$1/recreate
	funcExecuteRequest "POST" $url "application/x-www-form-urlencoded"

	output=`cat response.txt`
	status=`echo $output | jq '.status'`
    if [ $status == -1 ]; then
        echo "Started recreating the environment successfully"
		funcGetStatus "GET"
    else
        error=`echo $output | jq '.details'`
        echo "Error occurred. " $error
    fi
	funcRemoveTempFiles "respHeader.txt" "response.txt"
}

funcGetApplicationSnapshotDetails() {
	encodedFileName=$(echo $1 | sed -f urlencode.sed)
	url=$SERVER_URL/interop/rest/$API_VERSION/applicationsnapshots/$encodedFileName
	funcExecuteRequest "GET" $url "application/x-www-form-urlencoded"

	output=`cat response.txt`
	status=`echo $output | jq '.status'`
	if [ $status == 0 ]; then
		echo "Application details :"
		echo "Application snapshot name : " `echo $output | jq '.items[0].name'`
		echo "Application snapshot type : " `echo $output | jq '.items[0].type'`
		echo "Can be exported flag : " `echo $output | jq '.items[0].canExport'`
		echo "Can be imported flag : " `echo $output | jq '.items[0].canImport'`
		echo "Can be uploaded flag : " `echo $output | jq '.items[0].canUpload'`
		echo "Can be downloaded flag : " `echo $output | jq '.items[0].canDownload'`
		count=`echo $output | jq '.links | length'`
		i=0
		echo "Services details :"
		while [ $i -lt $count ]; do
			echo "Service : " `echo $output | jq '.links['$i'].rel'`
			echo "URL :" `echo $output | jq '.links['$i'].href'`
			echo "Action :" `echo $output | jq '.links['$i'].action'`
			echo ""
			i=`expr $i + 1`
		done
	else
		error=`echo $output | jq '.details'`
		echo "Error occurred. " $error
	fi
	funcRemoveTempFiles "respHeader.txt" "response.txt"
}

funcListFiles() {
	url=$SERVER_URL/interop/rest/$API_VERSION/applicationsnapshots
	funcExecuteRequest "GET" $url "application/x-www-form-urlencoded"

	list=`cat response.txt | jq 'select(.items != null) | .items[].name'`
	if [[ ! -z $list ]]; then
		echo $list
	else
		echo "No files found"
	fi
	funcRemoveTempFiles "respHeader.txt" "response.txt"
}


funcDeleteFile() {
	encodedFileName=$(echo $1 | sed -f urlencode.sed)
	url=$SERVER_URL/interop/rest/$API_VERSION/applicationsnapshots/$encodedFileName
	funcExecuteRequest "DELETE" $url "application/x-www-form-urlencoded"

	output=`cat response.txt`
	status=`echo $output | jq '.status'`
    if [ $status == 0 ]; then
        echo "Deleted successfully"
    else
        error=`echo $output | jq '.details'`
        echo "Error occurred. " $error
    fi
	funcRemoveTempFiles "respHeader.txt" "response.txt"
}

funcUploadFile() {
	infile=$1
	if [ ! -f $infile ]; then
		echo "File does not exist"
		exit 0
	fi
	encodedFileName=$(echo $infile | sed -f urlencode.sed)
	url="$SERVER_URL/interop/rest/$API_VERSION/applicationsnapshots/$encodedFileName/contents?q="
	filename=$( basename $infile)
	filesize=$( stat -c %s $infile)
	bs=52428800
	noOfPackets=$(($((filesize / bs)) + 1))
	uploadedsize=0
	isFirst=true
	count=1
	isLast="false"
	if [ $noOfPackets = 1 ]; then
	  isLast="true"
	fi
	tempFile=/u01/temp/$filename

	if [ ! -d "/u01/temp" ]; then
		mkdir /u01/temp
	fi

	while [ $uploadedsize -ne $filesize ]
	do
		skip=$uploadedsize
		temp=$((filesize - uploadedsize))
		if [ $temp -le $bs ]; then
			length=$temp
		else
			length=$bs
		fi
		echo "Skip : $skip"
		echo "Length : $length"
		
		(
			dd bs=1 skip=$skip count=0 &> /dev/null
			dd bs=$length count=1 of=$tempFile &> /dev/null
		) < "$infile"
		
		param=$(echo "{chunkSize=$length,isFirst=$isFirst,isLast=$isLast}" | sed -f urlencode.sed)
		urlwithparam="$url$param"
		echo $urlwithparam
		statusCode=`curl -X POST -s -w "%{http_code}" -T $tempFile -u "$USERNAME:$PASSWORD" -o "response.txt" -D "respHeader.txt" -H "Content-Type: application/octet-stream" "$urlwithparam"`

		funcRemoveTempFiles $tempFile

		if [ $statusCode == 200 ]; then
			output=`cat response.txt`
			status=`echo $output | jq '.status'`
			if [ $status != 0 ]; then
				error=`echo $output | jq '.details'`
				echo "Error occurred. " $error
				funcRemoveTempFiles "respHeader.txt" "response.txt"
				exit 0
			fi
		else
			echo "Error executing request"
			if [ $statusCode != 000 ]; then
				echo "Response error code : " $statusCode
				funcPrintErrorDetails "response.txt"
				funcRemoveTempFiles "respHeader.txt" "response.txt"
			fi
			exit 0
		fi
		funcRemoveTempFiles "respHeader.txt" "response.txt"
		uploadedsize=$((uploadedsize + length))
		isFirst="false"
		echo "isFirst : $isFirst"
		count=$((count + 1))
		if [ $count = $noOfPackets ]; then
			isLast="true"
		fi
		echo "Uploaded Size : $uploadedsize"
		echo "isLast : $isLast"
	done

	echo "Uploaded File Successfully"
}

funcDownloadFile() {
	filepath="/u01/$1"
	encodedFileName=$(echo $1 | sed -f urlencode.sed)
	url=$SERVER_URL/interop/rest/$API_VERSION/applicationsnapshots/$encodedFileName/contents
	statusCode=`curl -X GET -s -w "%{http_code}" -u "$USERNAME:$PASSWORD" -o $filepath -H "Content-Type: application/x-www-form-urlencoded" -D respHeader.txt $url`

	if [ $statusCode == 200 ]; then
		contentType=`echo $(grep 'Content-Type:' respHeader.txt) | tr -d [:space:]`
		if [ ! -z $contentType ] && [[ $contentType = *"application/json"* ]]; then
			output=`cat $filepath`
			error=`echo $output | jq '.details'`
			echo "Error occurred. " $error
			funcRemoveTempFiles $filepath
		else
			fileExtension=`echo $(grep -r "fileExtension: " respHeader.txt | awk  '{print ($2)}') | tr -d [:space:]`
			if [ ! -z $fileExtension ]; then
				if [[ ! $filepath =~ \.$fileExtension$ ]]; then
					mv $filepath $filepath.$fileExtension
				fi
			fi
			echo "Downloaded file successfully"
		fi
	else
		echo "Error listing files. "
		if [ $statusCode != 000 ]; then
			echo "Response error code : " $statusCode
			funcPrintErrorDetails $filepath
			funcRemoveTempFiles $filepath
		fi
	fi
	funcRemoveTempFiles "respHeader.txt"
}

funcImportSnapshot() {
	param=$(echo "{type:import}" | sed -f urlencode.sed)
	encodedFileName=$(echo $1 | sed -f urlencode.sed)
	url=$SERVER_URL/interop/rest/$API_VERSION/applicationsnapshots/$encodedFileName/migration?q=$param
	funcExecuteRequest "POST" $url "application/x-www-form-urlencoded"

	output=`cat response.txt`
	status=`echo $output | jq '.status'`
    if [ $status == -1 ]; then
        echo "Started importing successfully"
		funcGetStatus "POST"
    else
        error=`echo $output | jq '.details'`
        echo "Error occurred. " $error
    fi
	funcRemoveTempFiles "respHeader.txt" "response.txt"
}

funcExportSnapshot() {
	param=$(echo "{type:export}" | sed -f urlencode.sed)
	encodedFileName=$(echo $1 | sed -f urlencode.sed)
	url=$SERVER_URL/interop/rest/$API_VERSION/applicationsnapshots/$encodedFileName/migration?q=$param
	funcExecuteRequest "POST" $url "application/x-www-form-urlencoded"

	output=`cat response.txt`
	status=`echo $output | jq '.status'`
    if [ $status == -1 ]; then
        echo "Started exporting successfully"
		funcGetStatus "POST"
    else
        error=`echo $output | jq '.details'`
        echo "Error occurred. " $error
    fi
	funcRemoveTempFiles "respHeader.txt" "response.txt"
}

funcExecuteJob() {
	url="$SERVER_URL/HyperionPlanning/rest/$API_VERSION/applications/$APP_NAME/jobs"
	encodedJobName=$(echo $2 | sed -f urlencode.sed)
	if [ ! -z "$3" ]; then
		param="jobType=$1&jobName=$encodedJobName&parameters=$3"
	else
		param="jobType=$1&jobName=$encodedJobName"
	fi
	funcExecuteRequest "POST" $url $param "application/json"

	output=`cat response.txt`
	status=`echo $output | jq '.status'`
    if [ $status == -1 ]; then
        echo "Started executing job successfully"
		funcGetStatus "GET"
    else
        error=`echo $output | jq '.details'`
        echo "Error occurred. " $error
    fi
	funcRemoveTempFiles "respHeader.txt" "response.txt"
}

funcIntegrationScenarioImportMetadataIntoApplication() {
	funcUploadFile "DemoApplication_HSS_Vision.zip"
	funcExecuteJob "IMPORT_METADATA" "accountMetadata" "{importZipFileName=accounts.zip}"
	funcExecuteJob "CUBE_REFRESH" "cubeRefresh"
}

funcIntegrationScenarioImportDataRunCalcCopyToAso() {
    funcUploadFile "data.csv"
    funcExecuteJob "IMPORT_DATA" "loadingq1data" "{importFileName=data.csv}"
    funcExecuteJob "CUBE_REFRESH","cubeRefresh"
    funcExecuteJob "PLAN_TYPE_MAP" "CampaignToReporting" "{clearData=false}"
}

funcIntegrationScenarioExportMetadataAndDataAndDownloadFiles() {
    funcExecuteJob "EXPORT_METADATA" "exportentitymetadata" "{exportZipFileName=entitydata.zip}"
    funcExecuteJob "EXPORT_DATA" "Forecastdata" "{exportFileName=forecastdata.zip}"
    funcListFiles      
    funcDownloadFile "entitydata.zip"
    funcDownloadFile "forecastdata.zip"
}

funcIntegrationScenarioRemoveUnnecessaryFiles() {
    funcListFiles
    funcDeleteFile "entitymetadata.csv"
    funcDeleteFile "forecastdata.csv"
}

funcIntegrationScenarioExportDataAndDownloadFiles() {
    funcExecuteJob "EXPORT_DATA" "entitydata" "{exportFileName:entitydata.zip}"
    funcExecuteJob "EXPORT_DATA" "forecastdata" "{exportFileName:forecastdata.zip}"
    funcListFiles
    funcDownloadFile "entitydata.zip"
    funcDownloadFile "forecastdata.zip"
}

funcIntegrationScenarioRefreshTheApplication() {
    funcUploadFile "accounts.zip"
    funcExecuteJob "IMPORT_METADATA" "accountMetadata" "{importZipFileName:accounts.zip}"
    funcExecuteJob "CUBE_REFRESH" "cubeRefresh"
}

funcIntegrationScenarioCloneServiceInstance() {
	# Part 1 : Change SERVER_URL, USERNAME, PASSWORD, API_VERSION variables values to match those of first environment
	# Download file from source instance. 
	# Comment out all lines below Part 2
	# Uncomment the below line for the first step.
	# funcDownloadFile "Artifact Snapshot" 
	
	# Part 2 : Change SERVER_URL, USERNAME, PASSWORD, API_VERSION to match those of second environment.
	# Clone the service instance. 
	# Comment out code for download file.
	# Uncomment below lines
	funcRecreateService "PBCS"
	funcDeleteFile "Artifact Snapshot"
    funcUploadFile "Artifact Snapshot.zip"
	funcImportSnapshot "Artifact Snapshot"
}

funcIntegrationScenarioImportMetadataIntoApplication
funcIntegrationScenarioImportDataRunCalcCopyToAso
funcIntegrationScenarioExportMetadataAndDataAndDownloadFiles
funcIntegrationScenarioRemoveUnnecessaryFiles
funcIntegrationScenarioExportDataAndDownloadFiles
funcIntegrationScenarioRefreshTheApplication

Note on Proxy Setting: In case of proxies, set the proxy host and port as the system arguments.