
export PATH=/Users/$USER/work/INSTALL/pg-install/install_REL9_5_3/bin:$PATH
export DYLD_LIBRARY_PATH=/Users/$USER/work/INSTALL/pg-install/install_REL9_5_3/lib:$DYLD_LIBRARY_PATH

# initialise and start master with wal_log_hints
initdb -D /tmp/master
pg_ctl -D /tmp/master -o "-c listen_addresses='*' -c wal_level=hot_standby -c autovacuum=off -c hot_standby=on -c max_wal_senders=5 -c wal_log_hints=on -c max_prepared_transactions=5" start

# setup for replication
echo "host    replication     $USER        127.0.0.1/32            trust" >> /tmp/master/pg_hba.conf
echo "host    replication     $USER        ::1/128                 trust" >> /tmp/master/pg_hba.conf
sleep 2

# initialise and start standby
pg_basebackup -h localhost -R -x -D /tmp/standby 
pg_ctl -D /tmp/standby -o "-c port=5433 -c listen_addresses='*' -c wal_level=hot_standby -c autovacuum=off -c hot_standby=on -c max_wal_senders=5 -c wal_log_hints=on -c max_prepared_transactions=5" start
sleep 5


psql -c "create table testtab (a int, b char(100))" postgres
psql -c "insert into testtab select generate_series(1,1000), 'foo'" postgres
psql -c "insert into testtab select generate_series(1,1000), 'foo'" postgres
psql -c "delete from testtab where ctid > '(8,0)'" postgres

# take a lock on the table to prevent following vacuum from truncating it
psql -c "begin; lock table testtab in row share mode; prepare transaction 'p1'" postgres

# vacuum, update FSM but no truncation
psql -c "vacuum verbose testtab" postgres

# force a checkpoint
psql -c "checkpoint" postgres

# now do some more insert/deletes, another vacuum to ensure FPW writes are done
psql -c "insert into testtab select generate_series(1,1000), 'foo'" postgres
psql -c "delete from testtab where ctid > '(8,0)'" postgres
psql -c "vacuum verbose testtab" postgres

# ensure all buffers are now clean on the standby
psql -p 5433 -c "checkpoint" postgres

# release the lock, vacuum again which should lead to truncation
psql -c "rollback prepared 'p1'" postgres
psql -c "vacuum verbose testtab" postgres

psql -c "checkpoint" postgres
# wait long enough for standby to receive and apply all WAL
sleep 5

# now promote the standby
pg_ctl -D /tmp/standby promote
sleep 5
psql -p 5433 -c "checkpoint" postgres

# restart to discard in-memory copy of FSM
pg_ctl -D /tmp/standby restart
sleep 5

# FAIL
psql -p 5433 -c "insert into testtab select generate_series(1,1000), 'foo'" postgres
