#!/bin/bash

. lib/common

set -e

DBNAME="$(relation-get dbname)" || exit 1

initing="${GOGOCARTO_CODE}"/.initing-${DBNAME}
if [ -e "$initing" ]; then
    exit 0
fi


inited="${GOGOCARTO_CODE}"/.inited-${DBNAME}

MONGO_URL=mongodb://${TARGET_SERVICE_NAME}:27017


cat <<EOF >> ${GOGOCARTO_CODE}/.env

###> doctrine/mongodb-odm-bundle ###
MONGODB_URL=$MONGO_URL
MONGODB_DATABASE=$DBNAME
###< doctrine/mongodb-odm-bundle ###

DATABASE_NAME=$DBNAME

EOF

if [ -e "$inited" ]; then
    exit 0
fi

## came from ``Makefile`` in git's gogocarto source code. Target load-fixtures.
touch "$initing"
trap_add EXIT,ERR "rm -v \"$initing\""
symphony doctrine:mongodb:schema:create &&
symphony doctrine:mongodb:generate:hydrators &&
symphony doctrine:mongodb:generate:proxies &&
symphony doctrine:mongodb:fixtures:load -n || {
    err "Mongo database initialization failed."
    exit 1
}

touch "$inited"