#!/bin/bash

PGDATA1=pgdata1
PGDATA2=pgdata2
PGPORT1=7700
PGPORT2=7701

initdb -D ${PGDATA1}
initdb -D ${PGDATA2}

echo "wal_level=logical" >> ${PGDATA1}/postgresql.conf
echo "port=${PGPORT1}" >> ${PGDATA1}/postgresql.conf
echo "port=${PGPORT2}" >> ${PGDATA2}/postgresql.conf

pg_ctl -D ${PGDATA1} -l logfile_${PGDATA1} start
pg_ctl -D ${PGDATA2} -l logfile_${PGDATA2} start

psql -p ${PGPORT1} postgres -c "create table a(a int);"
psql -p ${PGPORT1} postgres -c "create table c(a int);"
psql -p ${PGPORT1} postgres -c "truncate table c;"
psql -p ${PGPORT1} postgres -c "create unlogged table zz(a bigint) with oids;"
psql -p ${PGPORT1} postgres -c "create publication a for table a;"

psql -p ${PGPORT2} postgres -c "create table a(a int);"
psql -p ${PGPORT2} postgres -c "create subscription aa connection 'port=7700 dbname=postgres' publication a;"

psql -p ${PGPORT1} postgres -c "insert into a values (1);"
psql -p ${PGPORT1} postgres -c "insert into zz select generate_series(1,4294950903);"

pg_ctl -D ${PGDATA1} -l logfile_${PGDATA1}_new restart
psql -p ${PGPORT1} postgres -c "truncate zz;"

psql -p ${PGPORT1} postgres << EOF
create temp table tempa(a int);
select * from pg_class where relfilenode = '16390';
insert into c values(1);
EOF

sleep 10
grep "unexpected duplicate" logfile_${PGDATA1}_new
pg_ctl -D ${PGDATA1} stop
pg_ctl -D ${PGDATA2} stop
rm -rf ${PGDATA1} ${PGDATA2} logfile_${PGDATA1} logfile_${PGDATA2}
