#! /bin/sh
set -ex

PGDATA=repro-btree-cleanup
PGDATABASE=repro_btree_cleanup
export PGDATA PGDATABASE PGPORT
unset PGUSER

# master
PGPORT=1
initdb
cat >$PGDATA/pg_hba.conf <<EOF
local all all ident
local replication all ident
EOF
cat >$PGDATA/postgresql.conf <<EOF
listen_addresses = ''
logging_collector = on
autovacuum = off
hot_standby = on
wal_level = hot_standby
archive_mode = on
archive_command = ':'
max_wal_senders = 1
wal_keep_segments = 5
vacuum_defer_cleanup_age = 10000
max_standby_archive_delay = 0
max_standby_streaming_delay = 0
EOF
pg_ctl -w start
createdb
psql -c "SELECT pg_start_backup('foo', true)"
cp -a $PGDATA standby_$PGDATA
psql -c 'SELECT pg_stop_backup()'

# standby
PGPORT=2
rm standby_$PGDATA/postmaster.pid
cat >standby_$PGDATA/recovery.conf <<EOF
standby_mode = 'on'
primary_conninfo = 'port=1'
EOF
pg_ctl -w -D standby_$PGDATA start
# This command's snapshot will conflict with recovery.
psql -c 'SELECT pg_sleep(600)' &

# Instigate on-the-fly deletion of index tuples.
PGPORT=1 psql -X <<EOSQL
CREATE TABLE t (x int);
CREATE UNIQUE INDEX t0 ON t(x);
BEGIN; INSERT INTO t SELECT * FROM generate_series(1, 10000); ROLLBACK;
-- To reproduce with a non-UNIQUE index, also uncomment these.
--SET enable_seqscan = off;
--SET enable_bitmapscan = off;
--SELECT count(*) FROM t WHERE x > 0;
BEGIN; INSERT INTO t SELECT * FROM generate_series(1, 10000); COMMIT;
EOSQL
sleep 1

PGPORT=2 pg_ctl -w -D standby_$PGDATA -m fast stop
PGPORT=1 pg_ctl -w -m fast stop
