#
#   aws-get-keys - Get AWS keys from AWS_PROFILE
#

function getTempCreds() {
    local creds_json
    creds_json=$(aws --output json sts get-session-token --duration-seconds 3600 --profile ${AWS_PROFILE})
    if [[ $? -ne 0 || ! $creds_json ]]; then
        echo "Cannot get credentials account '$aws_account': $creds_json" 1>&2
        exit 1
    fi

    local jq="jq --exit-status --raw-output"
    AWS_ACCESS_KEY_ID=$(echo "$creds_json" | $jq .Credentials.AccessKeyId)
    if [[ $? -ne 0 || ! $AWS_ACCESS_KEY_ID ]]; then
        echo "Failed to parse output for AWS_ACCESS_KEY_ID: $creds_json" 1>&2
        exit 1
    fi
    AWS_SECRET_ACCESS_KEY=$(echo "$creds_json" | $jq .Credentials.SecretAccessKey)
    if [[ $? -ne 0 || ! $AWS_SECRET_ACCESS_KEY ]]; then
        echo "Failed to parse output for AWS_SECRET_ACCESS_KEY: $creds_json" 1>&2
        exit 1
    fi
    AWS_SESSION_TOKEN=$(echo "$creds_json" | $jq .Credentials.SessionToken)
    if [[ $? -ne 0 || ! $AWS_SESSION_TOKEN ]]; then
        echo "Failed to parse output for AWS_SESSION_TOKEN: $creds_json" 1>&2
        exit 1
    fi
    export AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY AWS_SESSION_TOKEN
}

if [ -z "${AWS_ACCESS_KEY_ID}" ] ; then
    getTempCreds
fi

