#!/bin/bash

INSTALL=~/install/postgres
PGDATA1=~/junk/pgdata1
PGDATA2=~/junk/pgdata2
ARCHIVE=~/junk/archive

rm -fr $PGDATA1
rm -fr $PGDATA2
rm -fr $ARCHIVE
mkdir -m 700 $PGDATA2
mkdir $ARCHIVE

$INSTALL/bin/initdb -D $PGDATA1
cat << EOF >> $PGDATA1/postgresql.conf
  wal_level = archive
  max_prepared_transactions = 1
  archive_mode = on
  archive_command = 'test ! -f $ARCHIVE/%f  && cp %p $ARCHIVE/%f'
EOF
$INSTALL/bin/pg_ctl -D $PGDATA1 -w start
$INSTALL/bin/psql postgres << EOF
  ALTER DATABASE template0 ALLOW_CONNECTIONS TRUE;
  CREATE TABLE foo AS SELECT 42 AS id;
EOF

# make enough multixacts to fill exactly one page
$INSTALL/bin/psql postgres << EOF
  BEGIN;
  SELECT * FROM foo FOR SHARE;
  PREPARE TRANSACTION 'tx1';
EOF
( for ((i=0;i<2047;i++)) ; do echo "SELECT * FROM foo FOR SHARE;" ; done ) | $INSTALL/bin/psql postgres > /dev/null
$INSTALL/bin/psql postgres << EOF
  COMMIT PREPARED 'tx1';
EOF

# move oldest and next multixact to the first item on the second 
# page (which doesn't exist yet)
$INSTALL/bin/vacuumdb --freeze --all
$INSTALL/bin/psql postgres -c "SELECT pg_start_backup('foo', true)"

# copy all data files
cp -R $PGDATA1/* $PGDATA2/

# now copy control file (like baseback which does that last)
cp $PGDATA1/global/pg_control $PGDATA2/global/

$INSTALL/bin/psql postgres -c "SELECT pg_stop_backup()"

$INSTALL/bin/pg_ctl -D $PGDATA1 -w stop

cat > $PGDATA2/recovery.conf << EOF
  restore_command = 'cp $ARCHIVE/%f %p'
EOF

echo "---------------------------------------------------"
echo $PGDATA1
$INSTALL/bin/pg_controldata -D $PGDATA1 | grep MultiX
ls $PGDATA1/pg_multixact/offsets
echo "---------------------------------------------------"
echo $PGDATA2
$INSTALL/bin/pg_controldata -D $PGDATA2 | grep MultiX
ls $PGDATA2/pg_multixact/offsets
echo "---------------------------------------------------"

# ... and now try to start up with -D $PGDATA2...


