#!/bin/bash

set -x

# Call with a message as the argument
error() {
    echo "ERROR: ${*}"
    exit 1
}

if [[ -z "$AWS_ACCT_ID" ]]; then
    AWS_ACCT_ID=$1
    if [[ -z "$AWS_ACCT_ID" ]]; then
        error "Make sure AWS_ACCT_ID is set."
    fi
fi

AWS_STS_OUTPUT=$(aws sts assume-role --role-arn arn:aws:iam::${AWS_ACCT_ID}:role/controlplane-updater-jenkins --role-session-name jenkins-controlplane-updater)

if [[ -n "$AWS_STS_OUTPUT" ]]; then
    export AWS_ACCESS_KEY_ID=$(echo ${AWS_STS_OUTPUT} | jq -r .Credentials.AccessKeyId)
    export AWS_SECRET_ACCESS_KEY=$(echo ${AWS_STS_OUTPUT} | jq -r .Credentials.SecretAccessKey)
    export AWS_SESSION_TOKEN=$(echo ${AWS_STS_OUTPUT} | jq -r .Credentials.SessionToken)
else
    echo "Didn't succeed at assume role; the function update may not succeed. I assume you are running locally and know what you're doing."
fi

aws --region us-west-2 lambda update-function-code \
    --function-name arn:aws:lambda:us-west-2:${AWS_ACCT_ID}:function:controlplane-updater \
    --zip-file fileb://output/controlplane-updater.zip