#!/bin/bash

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

rm -fr $PGDATA
$INSTALL/bin/initdb -D $PGDATA

# We want a database with a next XID == FirstNormalTransactionId, but 
# we have to get there in several hops...

$INSTALL/bin/pg_resetxlog -x $((2 ** 30)) $PGDATA
$INSTALL/bin/pg_ctl -D $PGDATA -w start
$INSTALL/bin/psql postgres -c 'UPDATE pg_database SET datallowconn = true'
$INSTALL/bin/vacuumdb --freeze --all
$INSTALL/bin/pg_ctl -D $PGDATA -w stop

$INSTALL/bin/pg_resetxlog -x $((2 ** 30 * 2)) $PGDATA
$INSTALL/bin/pg_ctl -D $PGDATA -w start
$INSTALL/bin/vacuumdb --freeze --all
$INSTALL/bin/pg_ctl -D $PGDATA -w stop

$INSTALL/bin/pg_resetxlog -x $((2 ** 30 * 3)) $PGDATA
$INSTALL/bin/pg_ctl -D $PGDATA -w start
$INSTALL/bin/vacuumdb --freeze --all
$INSTALL/bin/pg_ctl -D $PGDATA -w stop

$INSTALL/bin/pg_resetxlog -x $((2 ** 32 - 2 ** 16)) $PGDATA

$INSTALL/bin/pg_ctl -D $PGDATA -w start
start_xid=` $INSTALL/bin/psql postgres --tuples -c "SELECT txid_current()" `
( for ((i = start_xid; i< 2 ** 32 - 1; i++)) ; do echo "SELECT txid_current();"; done ) | $INSTALL/bin/psql postgres > /dev/null
$INSTALL/bin/psql postgres -c "CHECKPOINT"
$INSTALL/bin/pg_ctl -D $PGDATA -w stop
