#!/bin/sh

export AWS_DEFAULT_REGION=$AWS_REGION
# this is the only way to get the service connection uuid
export SERVICE_CONNECTION_ID=$(env | \
            grep '^ENDPOINT_URL_' | \
            grep -v ENDPOINT_URL_SYSTEMVSSCONNECTION | \
            sed 's/^ENDPOINT_URL_//' | \
            sed 's/=.*$//' | tr -d '\n')
# use the service connection id and other environmental elements to get the URL from which to get an OIDC token
export OIDCTOKEN_URL="${SYSTEM_TEAMFOUNDATIONCOLLECTIONURI}${SYSTEM_TEAMPROJECTID}/_apis/distributedtask/hubs/build/plans/${SYSTEM_PLANID}/jobs/${SYSTEM_JOBID}/oidctoken?api-version=7.1-preview.1&serviceConnectionId=${SERVICE_CONNECTION_ID}"
# perform a curl POST to the appropriate endpoint to get a JSON OIDC token
export OIDCTOKEN_JSON=$(curl -d "" --request POST \
    --header "Authorization: Bearer $SYSTEM_ACCESSTOKEN" \
    --header "Content-Type: application/json" \
    $OIDCTOKEN_URL)

# uncomment for debug
# echo "OIDCTOKEN_URL=$OIDCTOKEN_URL"
# curl -vv -d "" --request POST \
#     --header "Authorization: Bearer $SYSTEM_ACCESSTOKEN" \
#     --header "Content-Type: application/json" \
#     $OIDCTOKEN_URL

# retrieve the actual token from the JSON response of the Azure endpoint
export OIDCTOKEN=$(echo "$OIDCTOKEN_JSON" | jq -r ".oidcToken")
# convert the token into base64 for use with the aws command line tool
export OIDCTOKEN_B64=$(echo "$OIDCTOKEN" | base64 )

# uncomment for debug
# echo "OIDCTOKEN=$OIDCTOKEN_B64"

# perform a sts:AssumeRoleWithWebIdentity call to get temporary credentials for AWS access
creds=$(aws sts assume-role-with-web-identity --duration-seconds 3600 --role-arn $AWS_ROLE_ARN --role-session-name $AWS_ROLE_SESSION_NAME --web-identity-token "$OIDCTOKEN")
# split the JSON formatted response from STS into invidual authentication components
export AWS_ACCESS_KEY_ID=$(echo $creds | jq -r ".Credentials.AccessKeyId")
export AWS_SECRET_ACCESS_KEY=$(echo $creds | jq -r ".Credentials.SecretAccessKey")
export AWS_SESSION_TOKEN=$(echo $creds | jq -r ".Credentials.SessionToken")
# echo the AWS tokens in the format consumed by Azure Pipelines task output, for use in downstream tasks
echo "##vso[task.setvariable variable=accessKeyId;isOutput=true]$AWS_ACCESS_KEY_ID"
echo "##vso[task.setvariable variable=secretAccessKey;isOutput=true]$AWS_SECRET_ACCESS_KEY"
echo "##vso[task.setvariable variable=sessionToken;isOutput=true]$AWS_SESSION_TOKEN"

# uncomment for debug
# aws sts get-caller-identity
