#!/usr/bin/env bash
# test for pg_replication rate limiting
#
# This is a small script which creates an instance to test pg_baseback rate
# limiting functionality. The instance will be filled with random data by
# pgbench.
# It does that by doing 4 runs with different rates specified and a last run
# without any limit so that it is visible, how fast it was.

if [ -z "$BINDIR" ]; then
  BINDIR="./bin"
fi

if [ -z "$ROOTDIR" ]; then
  ROOTDIR="./"
fi

PSQL="$BINDIR/psql -Atc"
PG_CTL="$BINDIR/pg_ctl"
INITDB="$BINDIR/initdb"
PGBENCH="$BINDIR/pgbench"
PG_BASEBACKUP="$BINDIR/pg_basebackup"

INST="${ROOTDIR}/test1"

# installation and configuration
$INITDB -D ${ROOTDIR}/test1 >> /dev/null
echo 'port=10001' >> $INST/postgresql.conf
echo 'wal_level=hot_standby' >> $INST/postgresql.conf
echo 'archive_mode=on' >> $INST/postgresql.conf
echo "archive_command='true'" >> $INST/postgresql.conf
echo 'max_wal_senders=1' >> $INST/postgresql.conf
echo 'checkpoint_segments=45' >> $INST/postgresql.conf

echo 'local  replication  all  trust' >> $INST/pg_hba.conf

# start the instance and fill it up
$PG_CTL -w -D $INST -s start
$PSQL "create database foo;" -p 10001 postgres
$PGBENCH -i -s 50 -p 10001 foo >> /dev/null 2>&1

echo -n 'size of the instance: '
du -sh $INST

# do the basebackup runs
for s in 50k 2500k 50m 500m; do
  echo "test with rate limit of '$s'"
  time $PG_BASEBACKUP -r $s -D "$ROOTDIR/test-${s}" -p 10001
  rm -R "$ROOTDIR/test-${s}"
done

echo 'test without any rate limit'
time $PG_BASEBACKUP -D "$ROOTDIR/test-unlimited" -p 10001
rm -R "$ROOTDIR/test-unlimited"

$PG_CTL -D $INST stop
rm -R "$INST"
