#!/bin/bash

# Node architecture
#
# central
#   | ^
#   v |
#   hub <---|
#    |      |
#    v      |
#   pos --->|

# Declarations

PORT_CENTRAL=5431
PORT_HUB=5432
PORT_POS=5433

DATA_CENTRAL=data_central
DATA_HUB=data_hub
DATA_POS=data_pos

LOG_CENTRAL=log.pub
LOG_HUB=log.sub
LOG_POS=log.pos

# Cleanup previous results

pg_ctl stop -D $DATA_CENTRAL
pg_ctl stop -D $DATA_HUB
pg_ctl stop -D $DATA_POS

rm -rf $DATA_CENTRAL $DATA_HUB $DATA_POS $LOG_POS $LOG_CENTRAL $LOG_HUB

# Setup central server

initdb -D $DATA_CENTRAL -U postgres -c wal_level=logical -c port=$PORT_CENTRAL

pg_ctl start -D $DATA_CENTRAL -l $LOG_CENTRAL

## Define objects for down-replication

psql -U postgres -p $PORT_CENTRAL -c "CREATE TABLE down (id int);"
psql -U postgres -p $PORT_CENTRAL -c "INSERT INTO down VALUES (generate_series(1, 100));"
psql -U postgres -p $PORT_CENTRAL -c "CREATE PUBLICATION pub_down FOR TABLE down;"

## Define another table for up-replication. The different table
## would be used here

psql -U postgres -p $PORT_CENTRAL -c "CREATE TABLE up (id int);"

# Setup hub server from the central

pg_basebackup -D $DATA_HUB -U postgres -p $PORT_CENTRAL
echo "port=$PORT_HUB
">> $DATA_HUB/postgresql.conf
pg_ctl start -D $DATA_HUB -l $LOG_HUB

## Define a subscription for down-replication

psql -U postgres -p $PORT_HUB -c "CREATE SUBSCRIPTION sub CONNECTION 'user=postgres port=$PORT_CENTRAL' PUBLICATION pub_down WITH (two_phase=true);"

# Setup pos server from the central again

pg_basebackup -D $DATA_POS -U postgres -p $PORT_CENTRAL
echo "port=$PORT_POS
">> $DATA_POS/postgresql.conf
pg_ctl start -D $DATA_POS -l $LOG_POS

## Define a subscription for down-replication

psql -U postgres -p $PORT_POS -c "CREATE SUBSCRIPTION sub_pos CONNECTION 'user=postgres port=$PORT_HUB' PUBLICATION pub_down WITH (two_phase=true);"

# Setup up-replication

## Define a publication on pos

psql -U postgres -p $PORT_POS -c "CREATE PUBLICATION pub_up FOR TABLE up;"

## Define a publication and a subscripion on hub

psql -U postgres -p $PORT_HUB -c "CREATE SUBSCRIPTION sub_up CONNECTION 'user=postgres port=$PORT_POS' PUBLICATION pub_up WITH (two_phase=false);"
psql -U postgres -p $PORT_HUB -c "CREATE PUBLICATION pub_up FOR TABLE up;"

## Define a subscription on central

psql -U postgres -p $PORT_CENTRAL -c "CREATE SUBSCRIPTION sub_up CONNECTION 'user=postgres port=$PORT_HUB' PUBLICATION pub_up WITH (two_phase=false);"

# Check the up-replication works well. Insert tuples to pos and
# count tuples on central

psql -U postgres -p $PORT_POS -c "INSERT INTO up VALUES (generate_series(101, 200));"
sleep 1s
psql -U postgres -p $PORT_CENTRAL -c "SELECT count(*) FROM up;"
