#!/bin/bash
# Creates the umami database and user if they don't already exist.
# Mounted as a postgres init script via docker-compose volumes.
set -e

psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" --dbname "$POSTGRES_DB" <<-EOSQL
    DO \$\$
    BEGIN
        IF NOT EXISTS (SELECT FROM pg_catalog.pg_roles WHERE rolname = 'umami') THEN
            CREATE ROLE umami WITH LOGIN PASSWORD 'umami_local';
        END IF;
    END
    \$\$;
    SELECT 'CREATE DATABASE umami OWNER umami'
    WHERE NOT EXISTS (SELECT FROM pg_database WHERE datname = 'umami')\gexec
EOSQL
