#! /usr/bin/env bash

####################################################################################################
# This file will be run from `global-setup.js`.
#
# It expects to be run with various DATABASE_* variables in the environment.
#
# We want running tests to be fast, and running this as as single shell script is faster than
# spawing multiple shells from Node.js.
####################################################################################################

SERVER_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && cd ../../.. && pwd )
MIGRATIONS_DIR="$SERVER_DIR/prisma/migrations"

if [ -z "$DATABASE_NAME" ]; then
  echo "Expected environment variables (e.g., DATABASE_NAME) to be set."
  exit 1
fi

if [ "$PUBLIC_PALOLO_ENV" != "local" ]; then
  echo "reset-test-database.sh can only be run locally"
  exit 1
fi

# First drop the database if it exists.  Wait until restarting tests to drop, so you can inspect the
# state of the database after test complete.
if psql ${DATABASE_NAME} -c '\q' 2>&1; then
  echo "Database $DATABASE_NAME found, dropping..."
  dropdb --force "$DATABASE_NAME" # Drop even if there are existing connections 🦫
fi

# Create the database anew.
createdb "$DATABASE_NAME"

psql -q -d "$DATABASE_NAME" -c "GRANT ALL PRIVILEGES ON DATABASE $DATABASE_NAME TO $DATABASE_USER;"

# Run Prisma migrations without the seed. Don't do this using Prisma itself, because that's pretty
# slow.  Just run the SQL files directly; that should be enough for testing.
for migration in "$MIGRATIONS_DIR"/*/; do
  # The migrations are lexographically sorted in the order that we want.

  # Run these migrations as the same database user that Prisma will use.
  PGPASSWORD="$DATABASE_PASSWORD" psql -q \
    -d "$DATABASE_NAME" \
    -U "$DATABASE_USER" \
    -f "$migration/migration.sql"
done
