apiVersion: v1
kind: ConfigMap
metadata:
  name: db-init-script-configmap
data:
  create-databases.sh: |
    #!/bin/bash

    set -e
    set -u

    function create_user_and_database() {
      local database=$1
      echo "  Creating user and database '$database'"
      psql -v ON_ERROR_STOP=1 --username postgres <<-EOSQL
          CREATE USER $database WITH PASSWORD '$MULTIPLE_DATABASES_PASSWORD';
          CREATE DATABASE $database;
          GRANT ALL PRIVILEGES ON DATABASE $database TO $database;
    EOSQL
    }

    function databaseExists() {
      local database=$1
      DBLIST=$(psql -v ON_ERROR_STOP=1 --username postgres -c 'SELECT datname FROM pg_database')
      echo $DBLIST | grep $database
    }

    if [ -n "$CREATE_MULTIPLE_DATABASES" ]; then
      echo "Multiple database creation requested: $CREATE_MULTIPLE_DATABASES"
      for db in $(echo $CREATE_MULTIPLE_DATABASES | tr ',' ' '); do
        if databaseExists $db ; then
          echo "Skipping database '$db' creation"
        else
          create_user_and_database $db
        fi
      done
      echo "Multiple databases created"
    fi
