file:
  {{ .Vars.persistence.mountPath }}:
    exists: true
    filetype: directory
    mode: "2775"
    owner: root
command:
  {{- $nodes := .Vars.postgresql.replicaCount }}
  check-repmgr-config:
    {{- $repmgr_password := .Vars.postgresql.repmgrPassword }}
    {{- $repmgr_user := .Vars.postgresql.repmgrUsername }}
    {{- $repmgr_database := .Vars.postgresql.repmgrDatabase }}
    {{- $repmgr_port := .Vars.postgresql.containerPorts.postgresql }}
    {{- $repmgr_endpoint := printf "-h postgresql-ha-postgresql -p %d" .Vars.service.ports.postgresql }}
    exec: PGPASSWORD={{ $repmgr_password }} psql -U {{ $repmgr_user }} -d {{ $repmgr_database }} {{ $repmgr_endpoint }} -c "SELECT conninfo FROM repmgr.nodes WHERE type = 'primary'"
    exit-status: 0
    stdout:
    - user={{ $repmgr_user }}
    - password={{ $repmgr_password }}
    - dbname={{ $repmgr_database }}
    - port={{ $repmgr_port }}
    - connect_timeout={{ .Vars.postgresql.repmgrConnectTimeout }}
  test-replication:
    # We need to first obtain the primary's host to perform write operations
    {{- $database := printf "db_%s" (randAlpha 5 | lower) }}
    exec: |
      export PGPASSWORD={{ $repmgr_password }} && \
      psql -U {{ $repmgr_user }} -d {{ $repmgr_database }} {{ $repmgr_endpoint }} -c "SELECT node_name FROM repmgr.nodes WHERE type = 'primary'" | grep postgresql-ha | \
      xargs -I '{}' psql -U {{ $repmgr_user }} -d {{ $repmgr_database }} -h '{}'.postgresql-ha-postgresql-headless -p {{ $repmgr_port }} -c "CREATE DATABASE {{ $database }};" && sleep 5 \
      {{ range $e, $i := until $nodes }}&& psql -U {{ $repmgr_user }} -d {{ $repmgr_database }} -h postgresql-ha-postgresql-{{ $i }}.postgresql-ha-postgresql-headless -p {{ $repmgr_port }} -c "SELECT datname FROM pg_database" | grep {{ $database }}{{ end }}
    exit-status: 0
  {{- $uid := .Vars.postgresql.containerSecurityContext.runAsUser }}
  {{- $gid := .Vars.postgresql.podSecurityContext.fsGroup }}
  check-user-info:
    # The UID and GID should always be either the one specified as vars (always a bigger number that the default)
    # or the one randomly defined by openshift (larger values). Otherwise, the chart is still using the default value.
    exec: if [ $(id -u) -lt {{ $uid }} ] || [ $(id -G | awk '{print $2}') -lt {{ $gid }} ]; then exit 1; fi
    exit-status: 0
