x-postgres-common: &postgres-common
  image: postgres:17.2
  healthcheck:
    test: "pg_isready -p $$PGPORT -U $$PGUSER"
    start_period: 20s
    interval: 1s
    timeout: 10s
    retries: 40
  command:
    - bash
    - "-c"
    - |
      set -e
      cat <<EOT > /docker-entrypoint-initdb.d/pg_hba.sh
      #!/bin/bash
      cat <<END > /var/lib/postgresql/data/pg_hba.conf
      local  all          all  trust
      local  replication  all  trust
      host   all          all  127.0.0.1/32  trust
      host   all          all  0.0.0.0/0     md5
      host   replication  all  127.0.0.1/32  trust
      host   replication  all  0.0.0.0/0     md5
      END
      EOT
      if [ -e /var/lib/postgresql/data/pg_hba.conf ]; then
        # We are here if it is NOT the initial container creation: update
        # pg_hba.conf still (since pg_hba.sh init script is run only once).
        bash /docker-entrypoint-initdb.d/pg_hba.sh
      fi
      if [ "$$POSTGRES_PRIMARY_HOST" != "" ]; then
        rm -rf /var/lib/postgresql/data/*
        echo "Copying the entire content of primary DB to this replica..."
        until PGPASSWORD=$$PGPASSWORD pg_basebackup --pgdata=/var/lib/postgresql/data -R -h $$POSTGRES_PRIMARY_HOST -p $$POSTGRES_PRIMARY_PORT -U $$PGUSER; do
          echo "Waiting for the primary PG server to boot..."
          sleep 1
        done
        chmod 0700 /var/lib/postgresql/data
        echo "Initial full DB copying from primary succeeded, switching to replication..."
      fi
      rm -f /var/run/postgresql/.s.PGSQL.*.lock
      rm -f /var/lib/postgresql/data/postmaster.pid
      /usr/local/bin/docker-entrypoint.sh \
        -c wal_level=logical \
        -c wal_keep_size=64 \
        -c synchronous_commit=off \
        -c max_connections=2000 \
        -c max_logical_replication_workers=10 \
        -c max_prepared_transactions=10 \
        -c log_line_prefix="%m [%p] %d " \
        -c pg_stat_statements.max=15000 \
        -c pg_stat_statements.track_utility=false

services:
  postgres:
    <<: *postgres-common
    environment:
      - PGPORT=55432
      - PGUSER=postgres
      - PGPASSWORD=postgres
      - POSTGRES_PASSWORD=postgres
    ports:
      - 0.0.0.0:55432:55432/tcp

  postgres-replica:
    <<: *postgres-common
    depends_on:
      postgres:
        condition: service_healthy
    environment:
      - PGPORT=55433
      - PGUSER=postgres
      - PGPASSWORD=postgres
      - POSTGRES_PASSWORD=postgres
      - POSTGRES_PRIMARY_HOST=postgres
      - POSTGRES_PRIMARY_PORT=55432
    ports:
      - 0.0.0.0:55433:55433/tcp
