#!/bin/bash
#
# Copyright (c) 2025, Cloudera, Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

set -e

create_db_if_not_exists() {
  local db_name="$1"
  local owner="$2"

  local db_exists=$(psql -U postgres -tAc "SELECT 1 FROM pg_database WHERE datname='${db_name}'")
  if [ "$db_exists" != 1 ]; then
    psql -v ON_ERROR_STOP=1 -U "$POSTGRES_USER" <<-EOSQL
CREATE DATABASE "$db_name";
GRANT ALL PRIVILEGES ON DATABASE "$db_name" TO "$owner";
EOSQL
    echo "Database '$db_name' created and privileges granted to '$owner'."
  else
    echo "Database '$db_name' already exists, skipping creation."
  fi
}

if [ -n "${POSTGRES_MULTIPLE_DATABASES}" ]; then

  owner="${POSTGRES_USER:-postgres}"

  # Create databases if they do not exist
  for db in $( echo "${POSTGRES_MULTIPLE_DATABASES//,/ }"); do
    # Check if the database already exists
    create_db_if_not_exists "$db" "$owner"
  done

fi
