#/bin/bash -x

rm -fr orig_pgdata copy_pgdata 93archive
mkdir 93archive
initdb -D orig_pgdata
cat >> orig_pgdata/postgresql.conf << EOF
  wal_level = archive
  archive_command = 'test ! -f ~/tmp/93archive/%f  && cp %p ~/tmp/93archive/%f'
  archive_mode = on
  log_checkpoints = on
  log_line_prefix = 'MASTER %m %p '
  checkpoint_segments = 3000
  max_wal_senders = 1
  wal_level = hot_standby
  port = 55446
EOF
export PGPORT=55446

cat >> orig_pgdata/pg_hba.conf << EOF
local	replication	alvherre	trust
EOF

pg_ctl -D orig_pgdata -w start
createdb mxact

psql mxact << EOF
  UPDATE pg_database set datallowconn = true;
  CREATE EXTENSION pageinspect;
  SELECT pg_burn_multixact(2048 * 32 * 10);
EOF

psql mxact -c "SELECT pg_start_backup('foo', true)"

cp -pr orig_pgdata/ copy_pgdata/
rm -fr copy_pgdata/pg_multixact

PGOPTIONS="-c vacuum_multixact_freeze_min_age=$((2048 * 32 * 7 + 2048 * 16 + 1024)) \
  -c vacuum_multixact_freeze_table_age=0" vacuumdb --all
ls orig_pgdata/pg_multixact/offsets/
psql mxact -c CHECKPOINT

PGOPTIONS="-c vacuum_multixact_freeze_min_age=$((2048 * 32 * 7 + 2048 * 14 + 1024)) \
  -c vacuum_multixact_freeze_table_age=0" vacuumdb --all
ls orig_pgdata/pg_multixact/offsets/
psql mxact -c CHECKPOINT

PGOPTIONS="-c vacuum_multixact_freeze_min_age=$((2048 * 32 * 4)) \
  -c vacuum_multixact_freeze_table_age=0" vacuumdb --all
ls orig_pgdata/pg_multixact/offsets/
psql mxact -c CHECKPOINT

cp -vpr orig_pgdata/pg_multixact/ copy_pgdata/
touch copy_pgdata/pg_multixact/offsets/0002

psql mxact -c "SELECT pg_stop_backup()"

pg_ctl -D orig_pgdata stop

cat >> copy_pgdata/recovery.conf << EOF
restore_command = 'cp ~/tmp/93archive/%f %p'
standby_mode = on
primary_conninfo = 'port = 55446'
EOF

cat >> copy_pgdata/postgresql.conf << EOF
port = 55447
log_error_verbosity = verbose
lc_messages = C
hot_standby = on
log_line_prefix = 'STANDBY %m %p '
EOF

pg_ctl -D orig_pgdata start
pg_ctl -D copy_pgdata -w start

