#!/bin/bash

# Cleanup previous results
pg_ctl stop -D data_N2
pg_ctl stop -D data_N1

rm -rf data_* *log

# Setup publisher instance
initdb -D data_N1 -U postgres -c "wal_level=logical"
pg_ctl -D data_N1 start -w -l N1.log

# Define a table and a publication
(
     echo -e "
create table foo (a int primary key, b int);
create publication pub for all tables;
insert into foo values (1, 1);
"
) | psql -U postgres


# Setup subscriber instance
initdb -D data_N2 -U postgres -c "port=9000" -c "track_commit_timestamp=on" -c "wal_receiver_status_interval=5s"
pg_ctl -D data_N2 start -w -l N2.log

# Define a table and a subscription
(
     echo -e "
create table foo (a int primary key, b int);
create subscription sub connection 'user=postgres' publication pub with (copy_data=off, detect_update_deleted = true);
"
) | psql -U postgres -p 9000

# Wait sometime to ensure launcher creates a replication slots
sleep 10s

# Insert the same tuple as publisher
(
     echo -e "
insert into foo values (1, 1);
"
) | psql -U postgres -p 9000


# Advance transaction ID to try to truncate commit_ts entries
(
     echo -e "
create extension xid_wraparound;
select consume_xids(60000000);
vacuum freeze;
"
) | psql -U postgres -p 9000


# Allow templete0 to connect to it
(
     echo -e "
alter database template0 allow_connections true;
vacuum freeze;
"
) | psql -U postgres -p 9000

# Update datfrozenxid for all the databases
psql -U postgres -p 9000 -d template1 -c "VACUUM FREEZE;"
psql -U postgres -p 9000 -d template0 -c "VACUUM FREEZE;"

# And cause a origin_differ conflict
psql -U postgres -c "update foo set b = 2;"
# psql -U postgres -c "delete from foo;"
