#!/bin/sh
set -e

DIR=$(cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd)
AWS_ENDPOINT=http://localhost:4566
APP_PORT=5005
AWS=$DIR/aws

echo "starting localstack"

onExit() {
  $DIR/stop
}

# Trap allows us to run some teardown when the shell is closed.
# I'm still confused why this isn't necessary for the test/script/test
# script which seems to hang on jest until until jest exits or sigint
# and then continues the parent script.
trap onExit EXIT

# start in detached/background mode
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 2
done

echo 'localstack running'

TABLE_EXISTS=$((
  $(AWS_ENDPOINT=$AWS_ENDPOINT $AWS dynamodb list-tables | jq ".TableNames | map(select(. == \"${AWS_DYNAMO_TABLE}\")) | length") > 0
))

# create the table if it doesn't exist
if [ $TABLE_EXISTS == 0 ]; then
  echo "create table '$AWS_DYNAMO_TABLE'"

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

DEBUG=song* PORT=$APP_PORT AWS_ENDPOINT=$AWS_ENDPOINT \
  nodemon \
    --watch "$DIR/../../lib" \
    --watch "$DIR/../../api" \
    --ext "ts" \
    --exec "node --inspect=9229 -r ts-node/register/transpile-only $DIR/server"

