#!/bin/bash
#
# This script is running on the teleport auth server side
# and is publishing tokens to SSM service so proxies and nodes can join the cluster

set -e
set -o pipefail

# Source variables set up by cloudformation template
. /etc/teleport.d/conf

TCTL=/usr/bin/tctl

# Proxy token authenticates proxies joining the cluster
PROXY_TOKEN=$(uuid)
${TCTL} nodes add --roles=proxy --ttl=4h --token=${PROXY_TOKEN}
aws ssm put-parameter --name /teleport/${TELEPORT_CLUSTER_NAME}/tokens/proxy --region ${EC2_REGION} --key-id=${TELEPORT_SSM_KEY_ARN} --type="SecureString" --value="${PROXY_TOKEN}" --overwrite

# Node token authenticates nodes joining the cluster
NODE_TOKEN=$(uuid)
${TCTL} nodes add --roles=node --ttl=4h --token=${NODE_TOKEN}
aws ssm put-parameter --name /teleport/${TELEPORT_CLUSTER_NAME}/tokens/node --region ${EC2_REGION} --key-id=${TELEPORT_SSM_KEY_ARN} --type="SecureString" --value="${NODE_TOKEN}" --overwrite

# Export CA certificate to SSM parameter store
# so nodes and proxies can check the identity of the auth server they are connecting to
CERT=$(${TCTL} auth export --type=tls)
aws ssm put-parameter --name /teleport/${TELEPORT_CLUSTER_NAME}/ca --region ${EC2_REGION} --type="String" --value="${CERT}" --overwrite
