#!/bin/bash
# This script runs on first PostgreSQL container start only
# (placed in /docker-entrypoint-initdb.d/)

set -e

{% for db in databases %}
echo "Creating database {{ db.name }} with user {{ db.user }}..."
psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" <<-EOSQL
  CREATE USER {{ db.user }} WITH PASSWORD '{{ db.password }}';
  CREATE DATABASE {{ db.name }} OWNER {{ db.user }};
  GRANT ALL PRIVILEGES ON DATABASE {{ db.name }} TO {{ db.user }};
EOSQL

psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" -d {{ db.name }} <<-EOSQL
  CREATE EXTENSION IF NOT EXISTS postgis;
EOSQL

{% endfor %}
echo "Database initialization complete."
