#!/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 from user-data
. /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} --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} --type="SecureString" --value="${NODE_TOKEN}" --overwrite

# Export CA pin hash to SSM parameter store
CA_PIN_HASH=$(tctl status | grep "CA pin" | awk '{print $3}')
aws ssm put-parameter --name /teleport/${TELEPORT_CLUSTER_NAME}/ca-pin-hash --region ${EC2_REGION} --type="String" --value="${CA_PIN_HASH}" --overwrite
