#!/bin/bash

##################
### Definition ###
##################
## posrts
port_pub=5433
port_sub=5434

## scale factor
SCALE=100

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

SOURCE=$1

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

./pg_ctl stop -D data_pub -w
./pg_ctl stop -D data_sub -w
rm -rf data* *log

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

./initdb -D data_pub 
cat << EOF >> data_pub/postgresql.conf
port=$port_pub
wal_level = logical
shared_buffers = 40GB
max_worker_processes = 32
max_parallel_maintenance_workers = 24
max_parallel_workers = 32
checkpoint_timeout = 1d
max_wal_size = 24GB
min_wal_size = 15GB
autovacuum = off
EOF

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

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

./initdb -D data_sub 

cat << EOF >> data_sub/postgresql.conf
port=$port_sub
shared_buffers = 40GB
max_worker_processes = 32
max_parallel_maintenance_workers = 24
max_parallel_workers = 32
checkpoint_timeout = 1d
max_wal_size = 24GB
min_wal_size = 15GB
autovacuum = off
track_commit_timestamp = on
EOF

./pg_ctl -D data_sub start -w -l sub.log
$INIT_COMMAND -p $port_sub

if [ $SOURCE = "head" ]
then
    ./psql -d postgres -p $port_sub -c "CREATE SUBSCRIPTION sub CONNECTION 'dbname=postgres host=localhost port=5433' PUBLICATION pub WITH (copy_data=false);"
else
    ./psql -d postgres -p $port_sub -c "CREATE SUBSCRIPTION sub CONNECTION 'dbname=postgres host=localhost port=5433' PUBLICATION pub WITH (copy_data=false, detect_update_deleted = on);"
fi
