#!/bin/sh

set -e

check_db_status() {
  echo "Checking if the database is empty..."
  if [ "$BUNDLE_WITH" = "postgresql" ]; then
    db_relations="$(LANG=C runuser -u postgres -- sh -c "psql ${DB_NAME} -c \"\d\"" 2>&1)"
    test "$db_relations" = "No relations found." || \
    test "$db_relations" = "Did not find any relations."
  elif [ "$BUNDLE_WITH" = "mysql" ]; then
    test -z "$(sudo mysql --defaults-file=/etc/mysql/debian.cnf -e "show tables from ${DB_NAME}")"
  else
    echo "BUNDLE_WITH variable should be set to postgresql or mysql"
    exit 1
  fi
}

# Generate secret token
bundle exec rake generate:secret_token

# Check if the db is already present
if check_db_status ; then
echo "Initializing database..."
	su diaspora -s /bin/sh -c 'bundle exec rake db:create db:migrate'
else
	echo "diaspora_production database is not empty, skipping database setup"
	echo "Running migrations..."
        su diaspora -s /bin/sh -c 'bundle exec rake db:migrate'
fi


