#!/bin/bash

test-postgres() {
    SERVICE=$1

    docker-up "${SERVICE}"

    # Wait up to two minutes for postgres to be available. It should come up
    # pretty quick on developer machines but CI/CD is slow.
    MAXCHECKS=40
    CHECKINTERVAL=3
    READY=
    for ((i=1;i<=MAXCHECKS;i++)); do
        log-info "waiting for ${SERVICE} ($i of $MAXCHECKS max)..."
        if docker compose exec -T "${SERVICE}" pg_isready -h localhost -U postgres >/dev/null; then
            READY=1
            break
        fi
        sleep "${CHECKINTERVAL}"
    done

    if [ -z ${READY} ]; then
        fail-now "timed out waiting for ${SERVICE} to be ready"
    fi

    log-info "running tests against ${SERVICE}..."
    ./postgres.test || fail-now "tests failed"
    docker-stop "${SERVICE}"
}

test-postgres postgres-13 || exit 1
test-postgres postgres-14 || exit 1
test-postgres postgres-15 || exit 1
test-postgres postgres-16 || exit 1
test-postgres postgres-17 || exit 1
