#!/bin/sh
set -eu

if [ -z "${TENANT_DATABASE_NAME:-}" ] || [ "${TENANT_DATABASE_NAME}" = "${POSTGRES_DB}" ]; then
    exit 0
fi

psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" --dbname postgres <<-EOSQL
    SELECT format('CREATE DATABASE %I', '${TENANT_DATABASE_NAME}')
    WHERE NOT EXISTS (
        SELECT 1
        FROM pg_database
        WHERE datname = '${TENANT_DATABASE_NAME}'
    ) \gexec
EOSQL
