#! /bin/bash
set -o errexit
set -o pipefail
set -o nounset

ITERATIONS=${ITERATIONS:-10}
SCALE=${SCALE:-300}

export PATH=$PWD/bin:$PATH

prep() {
  rm -rf foo
  mkdir foo
  pg_ctl initdb -D foo > /dev/null 2>/dev/null
}

update_config() {
cat - >> foo/postgresql.conf << EOF
checkpoint_segments = 1024
port = 54320
wal_level = hot_standby
EOF
}

start() {
  pg_ctl -l logfile start -D foo -w
  sync
}

test() {
  if grep wal_use_fallocate foo/postgresql.conf > /dev/null; then
    echo "With fallocate"
  else
    echo "Without fallocate"
  fi
  i=0
  while [ $i -lt $ITERATIONS ]; do
    time { pgbench -i -s ${SCALE} -p 54320  postgres >/dev/null 2>/dev/null ; }
    #pgbench -p 54320 -M extended  -T 120  postgres
    let i="$i+1"
  done
}

stop() {
  pg_ctl stop -D foo -w
}

prep
update_config
echo 'wal_use_fallocate = true' >> foo/postgresql.conf
start
test 2>&1 | tee -a timings
stop

prep
update_config
start
test 2>&1 | tee -a timings
stop

