#!/bin/bash
set -e

# adapt utilities.sql with dspace username from env variable
perl -pi -e 's/\$DSPACE_USER/$ENV{DSPACE_USER}/g;' /tmp/sql/utilities.sql

# populate postgres databases
psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" <<-EOSQL
    CREATE USER $DSPACE_USER WITH PASSWORD '$DSPACE_PASSWORD';
    CREATE DATABASE "$DSPACE_DBNAME" OWNER $DSPACE_USER ENCODING "UTF-8" TEMPLATE template0;
    CREATE DATABASE "$DSPACE_UTILSDBNAME" OWNER $DSPACE_USER ENCODING "UTF-8" TEMPLATE template0;
EOSQL

psql --username "$POSTGRES_USER" --set=utildir="/tmp/sql/" -p 5432 $DSPACE_UTILSDBNAME < /tmp/sql/utilities.sql
