base=$PWD/pgdata

PDIR=$base/primary

PORT1=5433
SDIR=$base/standby

PORT2=5434
SUBDIR=$base/subscriber

pg_ctl init -D $PDIR
cat << EOF >> $PDIR/postgresql.conf
wal_level=logical
standby_slot_names = 'pslot1'
logging_collector=on
log_filename='postgresql-%A.log'
cluster_name='primary'
EOF

pg_ctl start -D $PDIR

psql -d postgres << EOF
SELECT pg_create_physical_replication_slot('pslot1');
create table x(x int);
insert into x values(1);
create publication pub1 for all tables;
EOF

pg_basebackup -D $SDIR -R

cat << EOF >> $SDIR/postgresql.conf
port=$PORT1
primary_slot_name='pslot1'
synchronize_slot_names='*'
cluster_name='standby'
EOF

pg_ctl start -D $SDIR

pg_ctl init -D $SUBDIR
cat << EOF >> $SUBDIR/postgresql.conf
port=$PORT2
wal_level=logical
logging_collector=on
log_filename='postgresql-%A.log'
cluster_name='subscriber'
EOF

pg_ctl start -D $SUBDIR

psql -d postgres -p $PORT2 << EOF
create table x(x int);
create subscription sub1 connection 'host=localhost dbname=postgres' publication pub1;
EOF

pg_ctl restart -D $SDIR

sleep 3

pg_ctl stop -D $PDIR
pg_ctl promote -D $SDIR
psql postgres -p $PORT2 -c "alter subscription sub1 connection 'host=localhost port=$PORT1'"

psql postgres -p $PORT1 -c "insert into x values(2)"
