#!/bin/bash
set -e

cd /app

if [[ -z "$1" && -n "$WORKER_CMD" ]]; then
  set -- $WORKER_CMD
fi

source /scripts/setup_env

if [ "${ENABLE_SMOKESCREEN}" = "true" ] || [ "${START_SMOKESCREEN}" = "true" ]; then
  echo "Starting Smokescreen egress proxy..."
  /scripts/smokescreen &
fi

if [[ -z "${DO_NOT_CREATE_DATABASE}" && -z "$1" ]]; then
  bundle exec rake db:create RAILS_ENV=${RAILS_ENV}
fi

if [ -z "$1" ]; then
  bundle exec rake db:migrate RAILS_ENV=${RAILS_ENV}
else
  # Worker containers do not migrate; wait for the web container to finish
  # so that the process does not boot against an outdated schema.
  until bundle exec rake db:abort_if_pending_migrations RAILS_ENV=${RAILS_ENV}; do
    echo "Waiting for database migrations to complete..."
    sleep 10
  done
fi

if [[ -z "${DO_NOT_SEED}" && -z "$1" ]]; then
  set +e
  bundle exec rake db:seed RAILS_ENV=${RAILS_ENV}
  set -e
fi

if [ -z "$1" ]; then
  exec bundle exec puma -C config/puma.rb
else
  exec bundle exec rails runner "$@" RAILS_ENV=${RAILS_ENV}
fi
