{{- if and .Values.postgres.enabled .Values.postgres.auth.databases }}
apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ include "papercrate.fullname" . }}-postgres-init
  labels:
    {{- include "papercrate.labels" . | nindent 4 }}
    app.kubernetes.io/component: postgres
data:
  init-databases.sh: |
    #!/bin/sh
    set -e
    {{- range $name, $_ := .Values.postgres.auth.databases }}
    if ! psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" --dbname postgres \
      -tAc "SELECT 1 FROM pg_database WHERE datname = '{{ $name }}'" | grep -q 1; then
      psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" --dbname postgres \
        -c "CREATE DATABASE \"{{ $name }}\"";
    fi
    {{- end }}
    {{- $appRole := default "" .Values.postgres.auth.appRole }}
    {{- $appUser := default "" .Values.postgres.auth.appUsername }}
    {{- $appPassword := default "" .Values.postgres.auth.appPassword }}
    APP_ROLE="{{ $appRole }}"
    APP_USER="{{ $appUser }}"
    APP_PASSWORD="{{ $appPassword }}"
    APP_DATABASE="{{ default "papercrate" .Values.backend.env.databaseName }}"
    if [ -n "$APP_ROLE" ]; then
      psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" --dbname postgres <<-EOSQL
        DO $$
        BEGIN
            IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = '$APP_ROLE') THEN
                CREATE ROLE "$APP_ROLE" NOLOGIN;
            END IF;
        END
        $$;
EOSQL
    fi
    if [ -n "$APP_USER" ] && [ -n "$APP_PASSWORD" ]; then
      psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" --dbname postgres <<-EOSQL
        DO $$
        BEGIN
            IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = '$APP_USER') THEN
                CREATE ROLE "$APP_USER" LOGIN PASSWORD '$APP_PASSWORD';
            ELSE
                ALTER ROLE "$APP_USER" WITH LOGIN PASSWORD '$APP_PASSWORD';
            END IF;
            IF '$APP_ROLE' <> '' THEN
                GRANT "$APP_ROLE" TO "$APP_USER";
            END IF;
        END
        $$;
        GRANT CONNECT ON DATABASE "$APP_DATABASE" TO "$APP_USER";
        GRANT USAGE ON SCHEMA public TO "$APP_USER";
        ALTER ROLE "$APP_USER" SET search_path = 'tenant, shared, public';
        ALTER ROLE "$APP_USER" INHERIT;
EOSQL
    fi
    if [ -n "$PGDATA" ] && [ -f "$PGDATA/postgresql.conf" ]; then
      if grep -q "^max_connections" "$PGDATA/postgresql.conf"; then
        sed -i "s/^max_connections.*/max_connections = {{ .Values.postgres.maxConnections | default 200 }}/" "$PGDATA/postgresql.conf"
      else
        echo "max_connections = {{ .Values.postgres.maxConnections | default 200 }}" >> "$PGDATA/postgresql.conf"
      fi
    fi
{{- end }}
