#!/bin/sh

check_db_status() {
  echo "Checking if the database is empty..."
  if [ "$DB" = "postgres" ]; 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."
  else
    test -z "$(sudo mysql --defaults-file=/etc/mysql/debian.cnf -e "show tables from ${DB_NAME}")"
  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


