#!/bin/bash

port_pub=5431
port_sub=5432

echo 'Clean up'

pg_ctl stop -D data_N2
pg_ctl stop -D data_N1

rm -rf data_* *log

echo 'Set up'

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

cat << EOF >> data_N1/postgresql.conf
wal_level = logical
port = $port_pub
autovacuum = true
checkpoint_timeout = 1h
shared_buffers = '8GB'
wal_buffers = '1GB'
max_connections = '5000'
max_wal_size = 20GB
min_wal_size = 10GB
EOF

cat << EOF >> data_N2/postgresql.conf
wal_level = logical
port = $port_sub
autovacuum = true
checkpoint_timeout = 1h
shared_buffers = '8GB'
wal_buffers = '1GB'
max_connections = '5000'
max_wal_size = 20GB
min_wal_size = 10GB
EOF

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

(
     echo -e "create table tab (a int not null, b int);
alter table tab replica identity full;
insert into tab select 1,generate_series(1, 1000000, 1);
create publication pub for all tables;
"
) | psql -U postgres -p $port_pub

(
     echo -e "create table tab (a int not null, b int) partition by range (b);
create table tab_1 partition of tab for values from (minvalue) to (5000000);
create table tab_2 partition of tab for values from (5000000) to (maxvalue);
alter table tab replica identity full;
create subscription sub connection 'user=postgres port=$port_pub' publication pub with (synchronous_commit = remote_apply);
"
) | psql -U postgres -p $port_sub

cat << EOF >> data_N1/postgresql.conf
synchronous_standby_names  = 'sub'
EOF

pg_ctl reload -D data_N1
