#!/bin/bash

port_N1=5431
port_N2=5432

echo 'Clean up'

pg_ctl stop -D data_N1 -w
pg_ctl stop -D data_N2 -w

rm -r data_N1 data_N2 *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_N1
wal_sender_timeout = 0
log_line_prefix = '%m [%p] [%a] '
EOF

cat << EOF >> data_N2/postgresql.conf
wal_level = logical
port = $port_N2
max_sync_workers_per_subscription = 1
restart_after_crash = false
log_line_prefix = '%m [%p] [%b] '
EOF

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

for i in {0..10}
do
    echo "$i th challenge"
    psql -U postgres -p $port_N1 -c "CREATE TABLE tbl_$i (a int, b text)"
    psql -U postgres -p $port_N2 -c "CREATE TABLE tbl_$i (a int, b text)"

    psql -U postgres -p $port_N1 -c "INSERT INTO tbl_$i VALUES (1, 'a')"
done

psql -U postgres -p $port_N1 -c "CREATE PUBLICATION pub FOR ALL TABLES"
psql -U postgres -p $port_N2 -c "CREATE SUBSCRIPTION sub CONNECTION 'user=postgres dbname=postgres port=$port_N1' PUBLICATION pub"
