#!/bin/bash

export TEST_HOME=`pwd`
export before_out=_tmp_arc_before
export during_out=_tmp_arc_during
export PGDATA=data

rm -rf ${PGDATA}
rm -rf archive
mkdir -p archive

initdb -D data

cat <<EOL >> ${PGDATA}/postgresql.conf
archive_timeout = 10
wal_level = archive
archive_mode = on
archive_command = 'test ! -f ${TEST_HOME}/archive/%f && cp %p ${TEST_HOME}/archive/%f'
EOL

pg_ctl start -w
pgbench -i
pgbench -T 20
pg_ctl stop -w

cat <<EOL >> ${PGDATA}/postgresql.conf
restore_command = 'cp ${TEST_HOME}/archive/%f \"%p\"'
recovery_target_timeline = 'latest'
EOL
touch ${PGDATA}/recovery.signal

pg_ctl start -w

date
sleep 1
psql -c"create table test (c1 int);"

arcrs=0
psql -c"select * from pg_stat_archiver" > $before_out 2>&1
while [ $arcrs -eq 0 ]; do
  psql -c"insert into test (c1) values (generate_series(1,10));" > /dev/null 2>&1
  psql -c"select * from pg_stat_archiver" > $during_out 2>&1
  diff $before_out $during_out > /dev/null 2>&1
  arcrs=$?
done
date

pg_ctl stop -w

