#!/bin/sh

PGBIN=/home/euler/pg/bin

PGDATA1=/tmp/original
PGARCHIVE=/tmp/archive

# clean up
$PGBIN/pg_ctl stop -D $PGDATA1

rm -rf $PGDATA1 $PGARCHIVE
mkdir $PGDATA1 $PGARCHIVE

# new cluster
$PGBIN/initdb -D $PGDATA1

# new configuration
cp $PGDATA1/postgresql.conf $PGDATA1/postgresql.nrp

# configuration changes
sed -e 's/^max_connections = [0-9][0-9]*/max_connections = 20/' \
	-e 's/^#logging_collector = off/logging_collector = on/' \
	-e 's/^#log_checkpoints = off/log_checkpoints = on/' \
	-e "s/^#log_line_prefix = ''/log_line_prefix = '[%t %u@%r %d] '/" \
	-e 's/^#wal_level = minimal/wal_level = archive/' \
	-e 's/^#archive_mode = off/archive_mode = on/' \
	-e 's/^#archive_timeout = 0/archive_timeout = 1min/' \
	-e "s/^#archive_command = ''/archive_command = 'cp %p \/tmp\/archive\/%f'/" \
	-i $PGDATA1/postgresql.conf

# start original cluster
$PGBIN/pg_ctl start -D $PGDATA1
sleep 5

# base backup
$PGBIN/psql -c "SELECT pg_start_backup('test')" postgres
cd $PGDATA1 && tar -czf $PGARCHIVE/bkp.tgz --exclude=postmaster.pid --exclude=pg_log/* * && cd ~
$PGBIN/psql -c "SELECT pg_stop_backup()" postgres

# create restore points
$PGBIN/psql -c "SELECT pg_create_restore_point('nrp test 1')" postgres

$PGBIN/psql -c "CREATE DATABASE foo" postgres

$PGBIN/psql -c "SELECT pg_create_restore_point('nrp test 2')" postgres

$PGBIN/pgbench -i -s 5 foo

$PGBIN/psql -c "SELECT pg_create_restore_point('nrp test 3')" postgres

$PGBIN/psql -c "CREATE TABLE test AS SELECT generate_series(1, 8000) a" foo

$PGBIN/psql -c "SELECT pg_create_restore_point('nrp test 2')" postgres

$PGBIN/psql -c "DELETE FROM test WHERE a < 5000" foo

$PGBIN/psql -c "SELECT pg_create_restore_point('nrp test 5nrp test 5nrp test 5nrp test 5nrp test 5nrp test 5nrp test 5nrp test 5nrp test 5nrp test 5nrp test 5nrp test 5nrp test 5nrp test 5nrp test 5nrp test 5')" postgres

$PGBIN/pg_ctl stop -D $PGDATA1

exit 0
