#!/bin/bash

port_PUB=7651
port_SUB=7652

function cleanup_nodes()
{
	echo 'Clean up'

	pg_ctl stop -D data_PUB
	pg_ctl stop -D data_SUB

	rm -r data_PUB data_SUB *log
}


function setup_nodes()
{
	echo 'Set up'

	# Create publisher/subscriber
	initdb -D data_PUB
	initdb -D data_SUB

	cat << EOF >> data_PUB/postgresql.conf
wal_level = logical
port = $port_PUB
max_replication_slots=40
log_min_messages = debug1
force_stream_mode=true
autovacuum = off
EOF

	cat << EOF >> data_SUB/postgresql.conf
port = $port_SUB
max_logical_replication_workers=100
max_replication_slots=40
max_parallel_apply_workers_per_subscription=99
log_min_messages = debug1
autovacuum = off
EOF

	pg_ctl -D data_PUB start -w -l PUB.log
	pg_ctl -D data_SUB start -w -l SUB.log

# Create publication/subscription
psql -p $port_PUB << EOF
CREATE TABLE tbl(id int);
CREATE PUBLICATION pub1 FOR TABLE tbl;
EOF
 
psql -p $port_SUB << EOF
CREATE TABLE tbl(id int);
CREATE SUBSCRIPTION sub1
	CONNECTION 'port=$port_PUB'
	PUBLICATION pub1
	WITH (copy_data = off, streaming = parallel);
EOF
}

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

cleanup_nodes
setup_nodes

