#!/bin/bash

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

## prefix
PUB_PREFIX="/home/hayato/pub_mypostgres/bin"

## scale factor
SCALE=100

## pgbench init command
INIT_COMMAND="pgbench -i -U postgres 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 -U postgres
cat << EOF >> data_pub/postgresql.conf
port=5431
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
${PUB_PREFIX}/$INIT_COMMAND -p 5431
psql -U postgres -p 5431 -c "CREATE PUBLICATION pub FOR ALL TABLES;"

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

initdb -D data_sub -U postgres

cat << EOF >> data_sub/postgresql.conf
port=5432
autovacuum = false
shared_buffers = '30GB'
max_wal_size = 20GB
min_wal_size = 10GB
track_commit_timestamp = on
# log_min_messages = DEBUG1
EOF

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

(
    echo "CREATE TABLE pgbench_pub_history (tid int,bid int,aid bigint,delta int,mtime timestamp,filler char(22));"
    echo "CREATE TABLE pgbench_pub_tellers (tid int not null primary key,bid int,tbalance int,filler char(84));"
    echo "CREATE TABLE pgbench_pub_accounts (aid bigint not null primary key,bid int,abalance int,filler char(84));"
    echo "CREATE TABLE pgbench_pub_branches (bid int not null primary key,bbalance int,filler char(88));"
) | psql -p 5432 -U postgres

if [ $SOURCE = "head" ]
then
    psql -U postgres -p 5432 -c "CREATE SUBSCRIPTION sub CONNECTION 'port=5431 user=postgres' PUBLICATION pub;"
else
    psql -U postgres -p 5432 -c "CREATE SUBSCRIPTION sub CONNECTION 'port=5431 user=postgres' PUBLICATION pub WITH (detect_update_deleted = on);"
fi

sleep 5s
