#! /bin/bash
# Create target docdb endpoints from a list of source mongodb endpoints
# dms_target_endpoints.sh username password host port certificate_arn

get-sources() {
    aws dms describe-endpoints \
            --filters Name=endpoint-type,Values=source |
    jq -r '.Endpoints[].EndpointIdentifier' |
    sort
}

get-databases() {
    awk '{
        position = index($0, "-")

        identifier = substr($0, 0, position - 1)
        db = substr($0, position + 1)

        if (!(db in endpoints) || (db in endpoints && identifier == "production")) {
            endpoints[db] = identifier
        }

    }END{
        for (database in endpoints) {
            print(database)
        }
    }' $*
}

cleanup() {
    exec >&2

    rm -f $tmpfile*
}

username=$1
password=$2
server_name=$3
port=$4
certificate=$5
tmpfile=$(mktemp)

trap 'cleanup' EXIT

get-sources > $tmpfile.source.list
get-databases $tmpfile.source.list |
while read db
do
    command="aws dms create-endpoint \
            --endpoint-identifier $db \
            --endpoint-type target \
            --engine-name docdb \
            --username $username \
            --password $password \
            --server-name $server_name \
            --port $port \
            --database-name $db \
            --ssl-mode verify-full \
            --certificate-arn $certificate"

    if ! $command
    then
        echo $command
    fi
done