#!/bin/bash

##################
### Definition ###
##################

##sleep 5s

port_pub=5533
port_sub=5534

## scale factor
SCALE=$2

## pgbench init command
INIT_COMMAND="./pgbench -i -U postgres postgres -s $SCALE"

SOURCE=$1
WORKERS=$3

################
### clean up ###
################

./pg_ctl stop -m i -D data_pub -w
./pg_ctl stop -m i -D data_sub -w
rm -rf data*
rm pub.log
rm sub.log

#######################
### setup publisher ###
#######################

./initdb -D data_pub -U postgres
cat << EOF >> data_pub/postgresql.conf
port=$port_pub
autovacuum = false
shared_buffers = '30GB'
max_wal_size = 20GB
min_wal_size = 10GB
wal_level = logical
EOF

./pg_ctl -D data_pub start -w -l pub.log
$INIT_COMMAND -p $port_pub
./psql -U postgres -p $port_pub -c "CREATE PUBLICATION pub FOR ALL TABLES;"

#######################
### setup sublisher ###
#######################

./initdb -D data_sub -U postgres

cat << EOF >> data_sub/postgresql.conf
port=$port_sub
autovacuum = false
shared_buffers = '30GB'
max_wal_size = 20GB
min_wal_size = 10GB
track_commit_timestamp = on
# log_min_messages = DEBUG1
max_worker_processes = 100
max_logical_replication_workers = 50
max_parallel_apply_workers_per_subscription = $WORKERS
EOF

./pg_ctl -D data_sub start -w -l sub.log

## create tables only, no data
$INIT_COMMAND -Idtp -p $port_sub


## subscription definition is same in both head and patched case
./psql -U postgres -p $port_sub -c "CREATE SUBSCRIPTION sub CONNECTION 'port=$port_pub user=postgres' PUBLICATION pub;"


# Wait until all the table sync is done
REMAIN="f"

while [ "$REMAIN" = "f" ]
do
   # Sleep a bit to avoid running the query too much
    sleep 1s

    # Check pg_subscription_rel catalog. This query is ported from wait_for_subscription_sync()
    # defined in Cluster.pm.
    REMAIN=`./psql -qtA -U postgres -p $port_sub -c "SELECT count(1) = 0 FROM pg_subscription_rel WHERE srsubstate NOT IN ('r', 's');"`

    # Print the result for the debugging purpose
    echo $REMAIN
done


sleep 5s
