#!/bin/bash

shopt -s -o errexit nounset

# env
PROJ=non-arch-wal-on-recovery
PGPREFIX=/tmp/"$PROJ"
PGBIN="$PGPREFIX"/bin
PGDATA="${PGPREFIX}/data"
PGLOG="${PGPREFIX}/postgresq.log"

# cleanup previous test
[ -f "${PGDATA}/postmaster.pid" ] && ${PGBIN}/pg_ctl -s -D "$PGDATA" -W -m immediate stop
rm -rf "${PGDATA}"
mkdir -p "${PGDATA}"

# init new cluster
"$PGBIN"/initdb -U postgres -N -D "$PGDATA" &> /dev/null

# start cluster
PARAMS=(
    --wal_level=replica
    --archive_mode=on
    --archive_command=
    --log_min_messages=debug2
    --cluster_name="${PROJ}"
)
"$PGBIN"/postgres -D "$PGDATA" "${PARAMS[@]}" &> "$PGLOG" &

# wait for the start to complete
until "$PGBIN"/pg_isready -q; do sleep .5; done

"$PGBIN"/pgbench -qis 5

ls "${PGDATA}"/pg_wal/archive_status
pkill -SIGABRT -f "non-arch-wal-on-recovery: walwriter"

while ! grep 'write-ahead log file' "$PGLOG" ; do sleep 1; done

# stop cluster in background 
kill %1
wait %1
