#! /bin/bash

set -o errexit
set -o pipefail
set -o nounset
set +x

# Clean up previous test runs.
pg_ctl -D data stop || true
rm -rf ./data
rm -rf ./server-*.db/
rm -f ./ctl-pipe

# Create our test cluster.
initdb -D data
cat - > data/postgresql.auto.conf <<EOF
port = 6000
EOF

pg_ctl -D data -l data/logfile start

# Create a pipe for remote-controlling the client, and launch our psql instance.
mkfifo ./ctl-pipe
psql "host=localhost port=6000 dbname=template1" < ./ctl-pipe &

# Assign the write end of our pipe to fd 3. Make sure it works with a /conninfo.
exec 3>./ctl-pipe
echo '\conninfo' >&3

for i in {1..200}; do
    name=server-$i.db

    echo
    echo "testing $name..."

    # Create a new NSS database. We redirect all output to a log file because
    # OpenSSL apparently doesn't have any quiet modes.
    if ! ./init-nss "$name" > init-nss.log 2>&1; then
        echo "./init-nss failed; see ./init-nss.log" >&2
        exit 1
    fi

    # Point the cluster to this new database.
    cat - > data/postgresql.auto.conf <<EOF
port = 6000

ssl = on
ssl_database = '../$name'
EOF
    pg_ctl -D data -l data/logfile reload

    # Try to connect using the new database.
    # XXX everything is async and races; hence the sleeps.
    echo '\c "host=localhost port=6000 dbname=template1 sslmode=verify-ca ssldatabase='"$name"'"' >&3
    sleep .1
    echo '\conninfo' >&3
    sleep .1
done
