#!/bin/sh
set -e

LOCALSTACK_ENDPOINT=http://localhost:4566

# Check if the container is already running
if [ "$(docker ps -q -f name=songwhip-queue-localstack)" ]; then
  echo "stopping running localstack container..."
  docker stop songwhip-queue-localstack
fi

echo "start localstack"

docker run \
  --rm -d \
  -p 4566:4566 \
  -p 4510-4559:4510-4559 \
  -e DEBUG=1 \
  -v /var/run/docker.sock:/var/run/docker.sock \
  --name songwhip-queue-localstack \
  localstack/localstack:4.14

printf "waiting for %s/_localstack/health " "$LOCALSTACK_ENDPOINT"

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

echo ''
echo 'localstack ready'
