#!/bin/bash

port_N1=5431
port_N2=5432
port_N3=5433

common_tbl="create table tbl (a int primary key);"

function show_table_on_all_nodes()
{
    echo $1
    psql -U postgres -p $port_N1 -c "select a as N1 from tbl order by a"
    psql -U postgres -p $port_N2 -c "select a as N2 from tbl order by a"
    psql -U postgres -p $port_N3 -c "select a as N3 from tbl order by a"
}

echo 'Clean up'

pg_ctl stop -D data_N1
pg_ctl stop -D data_N2
pg_ctl stop -D data_N3

rm -r data_N1 data_N2 data_N3 *log

echo 'Set up'

initdb -D data_N1 -U postgres
initdb -D data_N2 -U postgres
initdb -D data_N3 -U postgres

cat << EOF >> data_N1/postgresql.conf
wal_level = logical
port = $port_N1
max_logical_replication_workers=100
max_replication_slots=40
autovacuum = off
EOF

cat << EOF >> data_N2/postgresql.conf
wal_level = logical
port = $port_N2
max_logical_replication_workers=100
max_replication_slots=40
autovacuum = off
EOF

cat << EOF >> data_N3/postgresql.conf
wal_level = logical
port = $port_N3
max_logical_replication_workers=100
max_replication_slots=40
autovacuum = off
EOF

pg_ctl -D data_N1 start -w -l N1.log
pg_ctl -D data_N2 start -w -l N2.log
pg_ctl -D data_N3 start -w -l N3.log

psql -U postgres -p $port_N1 -c "$common_tbl"
psql -U postgres -p $port_N2 -c "$common_tbl"
psql -U postgres -p $port_N3 -c "$common_tbl"

# =====================================================================================================================

echo '****************************************'
echo 'create set testset'
echo '****************************************'

psql -U postgres -p $port_N1 -c "SELECT lrg_create('testgroup', 'FOR ALL TABLES', 'user=postgres port=$port_N1', 'testnode1');"

sleep 1s

# =====================================================================================================================

echo '****************************************'
echo 'Attach to testset'
echo '****************************************'

psql -U postgres -p $port_N2 -c "SELECT lrg_node_attach('testgroup', 'user=postgres port=$port_N2', 'user=postgres port=$port_N1', 'testnode2')"
sleep 1s
psql -U postgres -p $port_N3 -c "SELECT lrg_node_attach('testgroup', 'user=postgres port=$port_N3', 'user=postgres port=$port_N2', 'testnode3')"
sleep 1s

# Insert some more data at every node to see that it is replicated everywhere
psql -U postgres -p $port_N1 -c "insert into tbl values (12);"
psql -U postgres -p $port_N2 -c "insert into tbl values (22);"
psql -U postgres -p $port_N3 -c "insert into tbl values (32);"

sleep 5s
show_table_on_all_nodes "Data inserted at N1,N2,N3 should be shared"

# detaching and dropping can be also done, do following if you are interested in
#psql -U postgres -p $port_N2 -c "SELECT lrg_node_detach('testgroup', 'testnode3');"
#psql -U postgres -p $port_N2 -c "SELECT lrg_node_detach('testgroup', 'testnode2');"
#psql -U postgres -p $port_N1 -c "SELECT lrg_drop('testgroup');"
