#!/usr/bin/env bash
set -e

DIR="$(cd "$(dirname "$0")" && pwd)"
DEV_DIR=$DIR/../scripts/aws

JEST_CMD="./node_modules/.bin/jest --config $DIR/../test/jest.config.ts --runInBand --detectOpenHandles $@"

echo ""
echo "starting database container …"
echo ""

"$DEV_DIR"/localstackStart

# uncomment to show localstack logs
# "$DEV_DIR"/localstackLogs &

"$DEV_DIR"/createQueues
"$DEV_DIR"/createLambda
"$DEV_DIR"/createLambdaQueueMapping
"$DEV_DIR"/createDynamoTable

echo "AWS_KEY: $AWS_KEY";
echo "AWS_SECRET: $AWS_SECRET";

JEST_EXIT_CODE=0

# run jest forwarding on any args passed to this script
# TZ env-var ensures node timezone is always UTC and is not inherited from host machine
TZ='UTC' \
AWS_KEY=${AWS_KEY} \
AWS_SECRET=${AWS_SECRET} \
$JEST_CMD || JEST_EXIT_CODE=$?

# once jest finishes stop the database container
"$DEV_DIR"/localstackStop

# exit using the jest exit code, this means if the tests fail
# this script will also exit with non-zero/error exit code
# and prevent subsequent scripts running (eg. pre-push)
exit $JEST_EXIT_CODE
