#!/bin/bash

set -e

PATH=~/pgsql.master/bin:$PATH
PGDATA_MASTER=~/pgsql.master/data-master
PGDATA_STANDBY=~/pgsql.master/data-standby

export PGDATABASE=postgres

initdb -D $PGDATA_MASTER
echo "wal_level=hot_standby" >> $PGDATA_MASTER/postgresql.conf
echo "checkpoint_segments=20" >> $PGDATA_MASTER/postgresql.conf
echo "wal_keep_segments=20" >> $PGDATA_MASTER/postgresql.conf
echo "max_wal_senders=5" >> $PGDATA_MASTER/postgresql.conf
echo "synchronous_commit=off" >> $PGDATA_MASTER/postgresql.conf
echo "local replication all trust" >>$PGDATA_MASTER/pg_hba.conf

pg_ctl -w -D $PGDATA_MASTER start

psql -c "create table foo (i serial, t text);"

pg_basebackup -D $PGDATA_STANDBY -R -c fast
echo "port=5433" >> $PGDATA_STANDBY/postgresql.conf
echo "hot_standby=on" >> $PGDATA_STANDBY/postgresql.conf

# start standby
pg_ctl -w -D $PGDATA_STANDBY start

# Start inserting rows
echo "INSERT INTO foo (t) VALUES ('foo')" > /tmp/hstestscript.sql
pgbench -n --file=/tmp/hstestscript.sql -T20 &

# checkpoint master while the test is running.
sleep 2
psql -c checkpoint

# kill master abruptly, so that it doesn't generate a shutdown checkpoint.
sleep 2
pg_ctl -D $PGDATA_MASTER stop -m immediate

# restart standby. It will start recovery at the non-shutdown checkpoint
# created above

pg_ctl -D $PGDATA_STANDBY restart -m fast -w

# Since we execute the INSERTs from one connection, there should be no gaps.
# So, if the count and max don't match, something's wrong.
psql -c "select count(*), max(i) from foo" -p 5433
