#!/usr/bin/env bash

# * Run a postgres server at localhost:${DB_PORT}
# * Wait for it to be up and running
# * Run the passed arguments as a command
# * Kill the postgres server
#
# Example usage: ./with-db.sh cabal test
#
# The application running in this context can use
# the DB_* variables to connect to postgres.
export DB_USER=opium
export DB_PASS=opium
export DB_NAME=opium
export DB_PORT=5442

# On error or exit: Kill the postgres container
function kill_db_container {
  docker kill "${CONTAINER_ID}" > /dev/null
}
trap kill_db_container EXIT

CONTAINER_ID=$(docker run --rm \
  -e "POSTGRES_USER=${DB_USER}" \
  -e "POSTGRES_PASSWORD=${DB_PASS}" \
  -e "POSTGRES_DB=${DB_NAME}" \
  -p "127.0.0.1:${DB_PORT}:5432" \
  --health-cmd pg_isready \
  --health-interval 0.25s \
  --detach \
  postgres:14-alpine)

# Setting --health-cmd above allows us to wait for postgres to be up
until [[ "$(docker inspect -f "{{.State.Health.Status}}" "${CONTAINER_ID}" || true)" = healthy ]]
do
  sleep 0.1
done

"$@"