#!/usr/bin/bash

# env
PGBIN=/tmp/fix/bin
#PGBIN=/usr/lib/postgresql/12/bin
PUB=/tmp/pub
SUB=/tmp/sub
PUB_PORT=5432
SUB_PORT=5433
TS=$(date +%FT%T)
PUB_LOG="$PUB"-"$TS".log
SUB_LOG="$SUB"-"$TS".log

unset PGPORT PGHOST PGDATABASE PGDATA LD_LIBRARY_PATH
export PGUSER=postgres
export PGOPTIONS="-c client_min_messages=ERROR"
export PATH="${PGBIN}:${PATH}"

function log {
    L=$1; shift
    echo "$(date +'%F %T') ${L}:  $@"
}

# cleanup
pkill "pgbench"

for i in "$PUB" "$SUB"; do
    test -d "$i" || continue
    test -f "$i"/postmaster.pid && "$PGBIN"/pg_ctl -w -s -D "$i" -m immediate stop;
    log LOG "stopped old instance in $i: $?"
    rm -r "$i"
done

# cluster
"$PGBIN"/initdb -U postgres -N "$PUB" &>/dev/null; log LOG "init publisher: $?"
echo "wal_level=logical" >> "$PUB"/postgresql.conf
echo "log_min_messages=debug1" >> "$PUB"/postgresql.conf
echo "log_error_verbosity=verbose" >> "$PUB"/postgresql.conf

"$PGBIN"/initdb -U postgres -N "$SUB" &>/dev/null; log LOG "init subscriber: $?"
echo "log_min_messages=debug1" >> "$SUB"/postgresql.conf
echo "log_error_verbosity=verbose" >> "$SUB"/postgresql.conf
echo "port=$SUB_PORT" >> "$SUB"/postgresql.conf

"$PGBIN"/pg_ctl -w -s -D $PUB -l "$PUB_LOG" start; log LOG "published started: $?"
"$PGBIN"/pg_ctl -w -s -D $SUB -l "$SUB_LOG" start; log LOG "subscriber started: $?"
"$PGBIN"/pgbench -p "$PUB_PORT" -qis 5
"$PGBIN"/pg_dump -p "$PUB_PORT" -s | "$PGBIN"/psql -qXp "$SUB_PORT" -o /dev/null

# fake activity
"$PGBIN"/pgbench -p "$PUB_PORT" -T 300 -c 1 &> /dev/null &

# replication setup
"$PGBIN"/psql -p "$PUB_PORT" -Xc "CREATE PUBLICATION prov FOR ALL TABLES"
"$PGBIN"/psql -p "$SUB_PORT" -Xc "CREATE SUBSCRIPTION sub
                  CONNECTION 'host=127.0.0.1 port=5432'
                  PUBLICATION prov"

# wait for the streaming
unset V;
until [ "$V" == "0" ]; do
    V=$("$PGBIN"/psql -p "$SUB_PORT" -AtXc "SELECT count(srsubstate)
                                            FROM pg_subscription_rel
                                            WHERE srsubstate <> 'r'"
    )
    log LOG "waiting for all table to be ready: $V"
    sleep 1
done

grep -E "subscription.*has finished" "$SUB_LOG"

sleep 2

log LOG "bugging it"
# this should trigger the bug
"$PGBIN"/psql -h 127.0.0.1 -p "$SUB_PORT" -Xc "ALTER TABLE pgbench_history ADD id SERIAL PRIMARY KEY"

sleep 5

grep -E "ERROR|WARNING" "$PUB_LOG" "$SUB_LOG"

