#!/usr/bin/env sh
#
# Usage: supermarket server
# Summary: Start the Rails server
#

set -e

. $SUPERMARKET_EXEC/shared.sh

command=$(cat <<EOH
as_postgres() {
  sudo su - postgres --command "psql --dbname=supermarket_development --command=\"\$@\""
}

db_created() {
  sudo su - postgres --command "psql -l" | grep supermarket_development 2>&1 > /dev/null
  return \$?
}

db_initialized() {
  as_postgres "\dt" | grep schema_migrations 2>&1 > /dev/null
  return \$?
}

db_migrated() {
  local schema_version="\$(ls db/migrate | tail -1 | cut -d'_' -f1)"
  as_postgres "SELECT version FROM schema_migrations WHERE version='\$schema_version';" | grep \$schema_version 2>&1 > /dev/null
  return \$?
}

./bin/rake db:create 2>&1 > /dev/null

if ! db_initialized; then
  ./bin/rake db:schema:load
fi

if ! db_migrated; then
  ./bin/rake db:migrate
fi

if ! db_seeded; then
  ./bin/rake db:seed
fi

bundle exec foreman start
EOH
)

in_supermarket "$command"
