#!/bin/sh

INSTALL=~/install/postgres
PGDATA=~/junk/pgdata

rm -fr $PGDATA
$INSTALL/bin/initdb -D $PGDATA
echo "max_prepared_transactions = 10" >> $PGDATA/postgresql.conf
$INSTALL/bin/pg_ctl -D $PGDATA -w start
$INSTALL/bin/psql postgres -c "UPDATE pg_database SET datallowconn = true"
$INSTALL/bin/psql postgres -c 'CREATE TABLE t AS SELECT generate_series(1, 100000) i'
$INSTALL/bin/pg_ctl -D $PGDATA -w stop

# Hop around the xid clock generating overlapping writable serializable
# transactions that will be written out to the SLRU if TEST_OLDSERXID is
# defined.

for xid in 65536 1073741824 2147483648 3221225472 65536 1073741824 ; do

  # To see the warning about exceeding 1bn serializable xids in master,
  # comment out the PREPARE TRANSACTION line after vacuumdb below and uncomment
  # this (though it generates a bunch of noise about wraparound danger):
  #$INSTALL/bin/pg_ctl -D $PGDATA -w start
  #$INSTALL/bin/psql postgres -c "BEGIN TRANSACTION ISOLATION LEVEL SERIALIZABLE; SELECT * FROM t; PREPARE TRANSACTION 'tx1';"
  #$INSTALL/bin/pg_ctl -D $PGDATA -w stop

  echo "========== setting next xid to $xid ========="
  $INSTALL/bin/pg_resetwal -x $xid $PGDATA
  $INSTALL/bin/pg_ctl -D $PGDATA -w start
  $INSTALL/bin/vacuumdb --freeze --all
  $INSTALL/bin/psql postgres -c "BEGIN TRANSACTION ISOLATION LEVEL SERIALIZABLE; SELECT * FROM t; PREPARE TRANSACTION 'tx1';"
  $INSTALL/bin/psql postgres -c "BEGIN TRANSACTION ISOLATION LEVEL SERIALIZABLE; SELECT * FROM t; UPDATE t SET i = i WHERE i = 42; COMMIT;"
  $INSTALL/bin/psql postgres -c "BEGIN TRANSACTION ISOLATION LEVEL SERIALIZABLE; SELECT * FROM t; UPDATE t SET i = i WHERE i = 42; COMMIT;"
  $INSTALL/bin/psql postgres -c "COMMIT PREPARED 'tx1'"
  $INSTALL/bin/pg_ctl -D $PGDATA -w stop

  echo "Contents of pg_serial:"
  ls $PGDATA/pg_serial/
done

