#!/bin/sh
set -e

DIR=$(cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd)
AWS=$DIR/../aws
TS_NODE=$DIR/../../node_modules/.bin/ts-node-transpile-only

echo "starting localstack"

# start in detached/background mode
SERVICES=dynamodb,sns,kms docker compose -f $DIR/docker-compose.yml up -d

echo "waiting for dynamodb at ${AWS_ENDPOINT}/health"

# ping the localstack /health endpoint until it shows dynamo is running
until (curl --silent ${AWS_ENDPOINT}/health | grep "\"dynamodb\": \"\(running\|available\)\"" > /dev/null); do
  printf '.'
  sleep 5
done

echo 'localstack running'

# create the table
$AWS dynamodb create-table \
  --table-name $AWS_DYNAMO_TABLE \
  --attribute-definitions \
    AttributeName=partitionKey,AttributeType=S \
    AttributeName=sortKey,AttributeType=S \
  --key-schema \
    AttributeName=partitionKey,KeyType=HASH \
    AttributeName=sortKey,KeyType=RANGE \
  --billing-mode PAY_PER_REQUEST > /dev/null

echo "created table '$AWS_DYNAMO_TABLE'"

# create a kms key used to encypt sensitive data before storing
# (`sed` removes first line which includes a comment)
export AWS_KMS_KEY_ID=$($AWS kms create-key | sed "1 d" | jq -r '.KeyMetadata.KeyId');
echo "created kms key '$AWS_KMS_KEY_ID'";

# create the sns topic and subscribe to it 
export SNS_TOPIC_ARN=$(PORT=$PORT $TS_NODE $DIR/../sns/setup-sns.ts)
echo "created topic arn '$SNS_TOPIC_ARN'"
