#!/bin/sh

set -x

# Remove a potentially pre-existing server.pid for Rails.
rm -rf /app/tmp/pids/server.pid
rm -rf /app/tmp/cache/*

echo "Waiting for mysql to become ready...."

# Let DATABASE_URL env take presedence over individual connection params.
# This is done to avoid printing the DATABASE_URL in the logs
$(docker/entrypoints/helpers/database_url.sh)

until nc -z -v -w30 $MYSQL_HOST $MYSQL_PORT
do
  echo "Waiting a second until the database is receiving connections..."
  # wait for a second before checking again
  sleep 1
done

echo "Database ready to accept connections."

bundle install

BUNDLE="bundle check"
bundle exec rails db:migrate
bundle exec rake db:seed_fu
bundle exec rake searchkick:reindex:all

until $BUNDLE
do
  sleep 2;
done

# Execute the main process of the container
exec "$@"
