apiVersion: v1
kind: ConfigMap
metadata:
  name: config-with-all-configs
  namespace: default
  labels:
    environment: acceptancetesting

data:

  postgres.conf: |
    # Replication configs
    listen_addresses = '*'
    max_wal_senders = 10
    max_connections = 100
    shared_buffers = 128MB

    # Logging
    #log_destination = 'stderr,csvlog'
    #logging_collector = on
    #log_directory = 'pg_log'
    #log_filename= 'postgresql-%Y-%m-%d_%H%M%S.log'


  primary_init_script.sh: |
    #!/bin/bash
    set -e

    dt=$(date '+%d/%m/%Y %H:%M:%S');
    echo "$dt - Running init script the 1st time Primary Kubegres container is created...";

    customDatabaseName="mydb"
    customUserName="mydbuser"

    echo "$dt - Running: psql -v ON_ERROR_STOP=1 --username $POSTGRES_USER --dbname $POSTGRES_DB ...";

    psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" --dbname "$POSTGRES_DB" <<-EOSQL
    CREATE DATABASE $customDatabaseName;
    CREATE USER $customUserName WITH PASSWORD '$POSTGRES_MYAPP_PASSWORD';
    \connect $customDatabaseName;
    CREATE TABLE account(user_id serial PRIMARY KEY, username VARCHAR (50) NOT NULL);
    INSERT INTO account VALUES (1, 'username1');
    INSERT INTO account VALUES (2, 'username2');
    GRANT ALL PRIVILEGES ON DATABASE "$customDatabaseName" to $customUserName;
    GRANT ALL ON "account" to $customUserName;
    EOSQL

    echo "$dt - Init script is completed";


  pg_hba.conf: |
    # TYPE  DATABASE        USER            ADDRESS                 METHOD
    # Replication connections by a user with the replication privilege
    host    replication     replication     all                     md5
    # As long as it is authenticated, all connections allowed except from "0.0.0.0/0"
    local   all             all                                     md5
    host    all             all             all                     md5
    host    all             all             0.0.0.0/0               reject


  backup_database.sh: |
    #!/bin/bash
    set -e

    dt=$(date '+%d/%m/%Y %H:%M:%S');
    fileDt=$(date '+%d_%m_%Y_%H_%M_%S');
    backUpFileName="$KUBEGRES_RESOURCE_NAME-backup-$fileDt.gz"
    backUpFilePath="$BACKUP_DESTINATION_FOLDER/$backUpFileName"

    echo "$dt - Starting DB backup of Kubegres resource $KUBEGRES_RESOURCE_NAME into file: $backUpFilePath";
    echo "$dt - Running: pg_dumpall -h $BACKUP_SOURCE_DB_HOST_NAME -U postgres -c | gzip > $backUpFilePath"

    pg_dumpall -h $BACKUP_SOURCE_DB_HOST_NAME -U postgres -c | gzip > $backUpFilePath

    if [ $? -ne 0 ]; then
      rm $backUpFilePath
      echo "Unable to execute a BackUp. Please check DB connection settings"
      exit 1
    fi

    echo "$dt - DB backup completed for Kubegres resource $KUBEGRES_RESOURCE_NAME into file: $backUpFilePath";
