#!/bin/bash
# usage: repro-writebuffers-assert.sh <bindir of an assert build>
# Run it in an empty directory.
BIN=$1
export PGPORT=54399 PGUSER=postgres

$BIN/initdb --no-data-checksums -A trust -U postgres -D primary >/dev/null
echo "wal_keep_size = 1GB" >> primary/postgresql.conf
echo "autovacuum = off" >> primary/postgresql.conf
$BIN/pg_ctl -D primary -o "-p 54399" -l primary.log -w start >/dev/null

$BIN/psql -X -q -At postgres <<SQL
create table t (i int, p text);
insert into t select g, repeat('x', 100) from generate_series(1, 40000) g;
create table filler (p text);
delete from t where i > 20000;
vacuum (freeze, truncate false) t;
select pg_backup_start('x', true);
-- truncates t, this dirties the VM page without an FPI
vacuum t;
insert into filler select repeat('f', 200) from generate_series(1, 150000);
-- gives the VM page a newer LSN
delete from t where i = 1;
checkpoint;
\! cp -R primary standby
\o standby/backup_label
select labelfile from pg_backup_stop(false);
SQL

cp primary/pg_wal/0* standby/pg_wal/
rm standby/postmaster.pid
touch standby/standby.signal
echo "shared_buffers = 1MB" >> standby/postgresql.conf
$BIN/pg_ctl -D standby -o "-p 54400" -l standby.log -w start >/dev/null
grep -E 'past current point|writing block|TRAP|terminated|read-only' standby.log

$BIN/pg_ctl -D standby -m immediate stop >/dev/null 2>&1
$BIN/pg_ctl -D primary -m immediate stop >/dev/null 2>&1
