#!/usr/bin/env bash
set -e

IFS=' ' # space is set as delimiter
read -ra dbs <<< "$DB_NAMES" # postgres db names are read into an array as tokens separated by IFS

for db in "${dbs[@]}"
do
    echo "Creating user/db $db"
    env PGPASSWORD="$MASTER_PASSWORD" psql -p "$PORT" --host "$ENDPOINT_ADDRESS" --username "$MASTER_USERNAME" --dbname "$DB_NAME"<<-EOSQL
        CREATE USER $db WITH PASSWORD '$MASTER_PASSWORD';
        CREATE DATABASE $db;
        GRANT ALL PRIVILEGES ON DATABASE $db TO $db;
EOSQL
done
