#!/bin/bash

set -e

# 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

if [[ -z "$NO_ASSUME_ROLE" ]]; then
    ROLE_ARN=arn:aws:iam::${AWS_ACCT_ID}:role/controlplane-updater-jenkins
    echo "about to assume role ${ROLE_ARN}"
    AWS_STS_OUTPUT=$(aws --region us-west-2 sts assume-role --role-arn "${ROLE_ARN}" --role-session-name jenkins-controlplane-updater)

    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)
fi

for metadata in $(find tmp/metadata -type f -name "*.metadata.json"); do
    echo "Calling lambda for payload ${metadata}"
    if [[ -f result ]]; then
        rm -f result || true
    fi

    aws --region us-west-2 lambda invoke \
        --function-name arn:aws:lambda:us-west-2:${AWS_ACCT_ID}:function:controlplane-updater result \
        --payload fileb://${metadata}
    cat result || true
    echo # Adds a newline since there isn't one in the result
done

rm -f result || true
