#!/bin/bash
# Locking service makes sure that there is only one auth server performing certain action,
# for example renewing or getting Let's Encrypt certificates

set -e
if [[ "${DEBUG:-false}" == "true" ]]; then
    set -x
fi

# Source variables from user-data
. /etc/teleport.d/conf

if [ ! -f /etc/teleport.d/role.auth ]; then
    echo "Not running 'auth' role, exiting with success"
    exit 0
fi

IMDS_TOKEN=$(curl -sS -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 300")
NOW=$(date +%s)
TTL=$((NOW+3660))
PROCESS=$(curl -sS -H "X-aws-ec2-metadata-token: ${IMDS_TOKEN}" http://169.254.169.254/latest/meta-data/local-hostname)
echo Locking $PROCESS for $TTL.

# Either renew the lease if agent still holds it, or grab the lease if it's expired
aws dynamodb put-item \
    --region ${EC2_REGION} \
    --table-name ${TELEPORT_LOCKS_TABLE_NAME} \
    --item  "{\"Lock\": {\"S\": \"/auth/servers\"}, \"Expires\": {\"S\": \"$TTL\"}, \"Process\": {\"S\": \"$PROCESS\"}}" \
    --condition-expression="(attribute_not_exists(Expires) OR Expires <= :timestamp) OR Process = :process"\
    --expression-attribute-values "{\":timestamp\":{\"S\":\"$NOW\"}, \":process\":{\"S\":\"$PROCESS\"}}"

# shellcheck disable=SC2181
if [ $? -eq 0 ]; then
    echo "Renewed or locked the lease for $PROCESS until $(date -d @$TTL)"
else
    echo "Could not get renew lease, locked by other process"
    exit 255
fi
