#!/bin/sh
set -eu

ROOT=$(CDPATH='' cd -- "$(dirname -- "$0")/.." && pwd)
cd "$ROOT"

if [ ! -f "$ROOT/.env" ]; then
  echo "Missing $ROOT/.env. Copy .env.example to .env first." >&2
  exit 1
fi

set -a
# shellcheck source=/dev/null
. "$ROOT/.env"
set +a

if [ "${DATABASE_MODE:-container}" != container ]; then
  echo "scripts/test.sh requires the isolated local DATABASE_MODE=container setup." >&2
  exit 1
fi

: "${POSTGRES_USER:?Set POSTGRES_USER in .env}"
: "${POSTGRES_PASSWORD:?Set POSTGRES_PASSWORD in .env}"

docker compose -p who_need_help up -d --wait db
docker build --target test --tag who-need-help:test .

exec docker run --rm \
  --network who_need_help_internal \
  --env MIX_ENV=test \
  --env DB_HOST=db \
  --env "DB_USER=$POSTGRES_USER" \
  --env "DB_PASSWORD=$POSTGRES_PASSWORD" \
  --env TEST_POOL_SIZE="${TEST_POOL_SIZE:-10}" \
  who-need-help:test \
  mix test
