#!/bin/bash

if [ "$RAILS_ENV" = "production" ] && [ "$DB_ADAPTER" = "postgresql" ]; then
  while ! curl http://$DB_HOST:${DB_PORT:-5432}/ 2>&1 | grep '52'
  do
    echo "Waiting for postgres to start up ..."
    sleep 1
  done
fi

db_create="$(RAILS_ENV=$RAILS_ENV bundle.%{ruby_suffix} exec rake.%{ruby_suffix} db:create 2>&1)"
echo $db_create

if [[ $db_create == *"already exists"* ]]; then
  echo ">>> Database migration"
  bundle.%{ruby_suffix} exec rake.%{ruby_suffix} db:migrate
else
  echo ">>> Database initialization"
  bundle.%{ruby_suffix} exec rake.%{ruby_suffix} db:schema:load
fi

bundle.%{ruby_suffix} exec rake.%{ruby_suffix} assets:precompile

exec bundle.%{ruby_suffix} exec puma.%{ruby_suffix} -C config/puma.rb
