#!/usr/bin/env bash
# shellcheck disable=SC2188

set -eo pipefail

<<COMMENT
This script does the setup on the Docker image on reboot for local development; it is called
from docker-compose.yml.

The primary difference between this script and docker_eks_setup.sh is to:

1. Work around a Prisma bug: https://github.com/prisma/prisma/issues/12598
2. Run migrations and record deployments.
3. Create queues.
COMMENT

if [[ -z "${DEPLOYED_AT}" ]]; then
	export DEPLOYED_AT=$(date -u +%FT%TZ)
fi

set -u

# Prisma doesn't want to resolve the postgres container, so we manually resolve it.
# Then `secrets.ts` will override the DATABASE_HOST and DATABASE_PORT in the generated .env
# using these environment variables.
#
# Do this *before* base setup so that it applies to the run of `secrets.ts` therein.
export DATABASE_HOST=$(nslookup "${DATABASE_HOST?}" | awk '/^Address: / { print $2 ; exit }')

# Base setup.
export PALOLO_ENV=${PALOLO_ENV:-docker}
cd "$(dirname $(dirname "$0") )"
scripts/docker_base_setup.sh

cd packages/server

# Optionally run server or worker; default server.
PALOLO_COMMAND=${PALOLO_COMMAND:-server}
case $PALOLO_COMMAND in
  (server|worker) ;; # OK
  (*) printf >&2 'Error, invalid command ${PALOLO_COMMAND}...\n'; exit 1;;
esac

# Run migrations / record deployments only when running the server.
if [[ "${PALOLO_COMMAND}" == "server" ]]; then
    time pnpm run prisma migrate reset --force --skip-generate --skip-seed
    # Run a tiny seed only so this is quicker on local.
    time pnpm run seed --tiny

    # TODO: do we actually want to run this locally? Does it matter?
    ../../scripts/record-completed-deployment.sh "${GIT_SHA?}"
fi

# Configure worker only when running the worker.
if [[ "${PALOLO_COMMAND}" == "worker" ]]; then
    time pnpm run worker --configure
fi

# Let's go!
exec node --import=tsx src/"${PALOLO_COMMAND}".ts
