#!/bin/bash

export PGUSER=postgres
export PGDATABASE=postgres
export PGPORT=5432

SYNCNAME=server

initdb t1
cat <<_EOF_ >>t1/postgresql.conf
shared_buffers = 1GB
checkpoint_completion_target = 0.9
autovacuum = off
max_wal_size = 32000MB
log_checkpoints = on
wal_log_hints = on
log_statement = all
log_min_duration_statement = 0
_EOF_

pg_ctl -D t1 start -w
pg_basebackup -D t2 -R --checkpoint=fast -d "host=localhost port=$PGPORT user=$PGUSER application_name=$SYNCNAME"

cat <<_EOF_ >>t2/postgresql.conf
port = 5433
_EOF_

pg_ctl -D t2 start -w

psql -c "ALTER SYSTEM SET synchronous_standby_names TO $SYNCNAME"
psql -c "SELECT pg_reload_conf();"

pgbench -i -s 20 -Idtgp
psql -c "UPDATE pgbench_accounts SET abalance = 0" 

# CHECKPOINT and reload synchronous_standby_names in background.
{ 
sleep 10
psql -c "CHECKPOINT ;" &
sleep 0.1
psql -c "ALTER SYSTEM RESET synchronous_standby_names;"
psql -c "SELECT pg_reload_conf();"
} &

# Shut down the synchronous standby while transactions are running. 
# Commit operations will be delayed until synchronous_standby_names is reset.
# If a checkpoint is in progress in the background, COMMIT will continue to wait for
# the CHECKPOINT to complete even after synchronous_standby_names has been reloaded.
psql <<_EOF_
begin;
CREATE TABLE hoge(a int);
\! sleep 5
\! pg_ctl -D t2 stop -mi 
\! sleep 0.1
SELECT current_timestamp, 'COMMIT start';
COMMIT;
SELECT current_timestamp, 'COMMIT end';
_EOF_

