#!/bin/bash

port_PUB=5431
port_SUB=5432

echo 'Clean up'

pg_ctl stop -D data_PUB -w
pg_ctl stop -D data_SUB -w

rm -r data_PUB data_SUB *log

echo 'Set up'

initdb -D data_PUB -U postgres
initdb -D data_SUB -U postgres

cat << EOF >> data_PUB/postgresql.conf
wal_level = logical
port = $port_PUB
EOF

cat << EOF >> data_SUB/postgresql.conf
wal_level = logical
port = $port_SUB
EOF

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


# Initial setup

psql -U postgres -p $port_PUB << EOF
CREATE TABLE tbl1 (a text primary key, should_replicate bool NOT null DEFAULT false);
CREATE UNIQUE INDEX pub_idx on tbl1(a, should_replicate);
ALTER TABLE tbl1 REPLICA IDENTITY USING INDEX pub_idx;
CREATE PUBLICATION pub FOR TABLE tbl1 WHERE (should_replicate IS true);
INSERT INTO tbl1 VALUES ('PK on tbl1', true);
EOF

psql -U postgres -p $port_SUB << EOF
CREATE TABLE tbl1 (a text primary key, should_replicate bool NOT null DEFAULT false);
CREATE TABLE tbl2 (id int primary key, fk text NOT NULL REFERENCES tbl1 ON UPDATE CASCADE);
CREATE SUBSCRIPTION sub CONNECTION 'port=$port_PUB user=postgres' PUBLICATION pub;
EOF

# Wait until initial sync is done
sleep 5s

# Insert data on subscriber
psql -U postgres -p $port_SUB << EOF
INSERT INTO tbl2 VALUES (1, 'PK on tbl1');
EOF

# Check data
psql -U postgres -p $port_SUB << EOF
SELECT * FROM tbl1;
SELECT * FROM tbl2;
EOF

# Update tuple on publisher, this will be propagated as DELETE command
psql -U postgres -p $port_PUB << EOF
UPDATE tbl1 SET should_replicate = false
EOF
sleep 5s

# Check data again. The tuple in tbl2 refers non-existent line
psql -U postgres -p $port_SUB << EOF
SELECT * FROM tbl1;
SELECT * FROM tbl2;
EOF
