#!/bin/sh
# Starts the containers for the "no pg_hba.conf entry for host" measurements.
# One official postgres image per major version, plus three extra 17 containers:
#   -default  the official image, untouched
#   -listen   listen_addresses = 'localhost'
#   -typo     used for the restart-with-a-typo test
# Everything listens on 127.0.0.1 only. The password "test" is a test value.
#
#   PREFIX=pghba BASE=55800 ./setup.sh
set -eu
PREFIX=${PREFIX:-pghba}
BASE=${BASE:-55800}
VERSIONS=${VERSIONS:-"12 13 14 16 17 18"}
NET="$PREFIX-net"

docker network inspect "$NET" >/dev/null 2>&1 || docker network create "$NET" >/dev/null

start() { # name port image [server args]
  name=$1; port=$2; image=$3; shift 3
  docker rm -f "$name" >/dev/null 2>&1 || true
  docker run -d --name "$name" --network "$NET" -p "127.0.0.1:$port:5432" \
    -e POSTGRES_PASSWORD=test "$image" "$@" >/dev/null
  echo "$name 127.0.0.1:$port $image $*"
}

i=0
for v in $VERSIONS; do start "$PREFIX-$v" $((BASE + i)) "postgres:$v"; i=$((i + 1)); done
start "$PREFIX-default" $((BASE + 6)) postgres:17
start "$PREFIX-listen"  $((BASE + 7)) postgres:17 -c listen_addresses=localhost
start "$PREFIX-typo"    $((BASE + 8)) postgres:17

# Wait until each server is the real one: the init server of the entrypoint
# listens on the Unix socket only, the real one also on TCP.
for c in $(docker ps --filter "name=^$PREFIX-" --format '{{.Names}}'); do
  n=0
  until docker logs "$c" 2>&1 | grep -q 'listening on IPv4' \
     && docker exec "$c" pg_isready -U postgres -q; do
    n=$((n + 1)); [ $n -gt 60 ] && { echo "$c did not come up" >&2; exit 1; }
    sleep 1
  done
done
echo "ready"
