#!/usr/bin/bash

set -e

PATH_OLD=$PATH
DATADIR=/mnt/pgdata/data-vacuum

for rows in 50000000 500000000; do

	for wal in logged unlogged; do

		PATH=/mnt/data/builds/master/bin:$PATH_OLD

		pg_ctl -D $DATADIR -l pg.log stop || true
		pg_ctl -D $DATADIR -l pg.log start

		dropdb --if-exists test
		createdb test

		if [ "wal" == "logged" ]; then
			psql test -c "create table test_vacuum (a bigint) with (fillfactor=50)"
		else
			psql test -c "create unlogged table test_vacuum (a bigint) with (fillfactor=50)"
		fi

		psql test -c "insert into test_vacuum select i from generate_series(1,$rows) s(i)"
		psql test -c "vacuum freeze test_vacuum"
		psql test -c "checkpoint"

		psql test -c "\d+"

		for run in $(seq 1 3); do

			for eic in 1 10 32; do

				for perc in 0.01 0.001 0.0005 0.0002 0.0001 0.000075 0.00005 0.000025 0.00001 0.000001; do

					for build in master master-streaming; do

						PATH=/mnt/data/builds/$build/bin:$PATH_OLD

						pg_ctl -D $DATADIR -l pg.log stop
						pg_ctl -D $DATADIR -l pg.log start

						psql test -c "update test_vacuum set a=a where random() < $perc"

						pg_ctl -D $DATADIR -l pg.log restart
						sudo ./drop-caches.sh

						s=$(psql -t -A test -c "select extract(epoch from now())")

						psql test > vacuum.log 2>&1 <<EOF
set effective_io_concurrency = $eic;
set maintenance_io_concurrency = $eic;
vacuum (verbose, freeze) test_vacuum;
EOF
						cat vacuum.log

						pages_remain=$(grep '^pages:' vacuum.log | awk '{print $4}')
						pages_scanned=$(grep '^pages:' vacuum.log | awk '{print $6}')
						avg_read=$(grep '^avg read rate:' vacuum.log | awk '{print $4}')
						avg_write=$(grep '^avg read rate:' vacuum.log | awk '{print $9}')

						e=$(psql -t -A test -c "select extract(epoch from now())")
						d=$(psql -t -A test -c "select ($e - $s)")

						echo "$rows $wal $run $eic $perc $build $d $pages_remain $pages_scanned $avg_read $avg_write" >> results.csv

					done

				done

			done

		done

	done

done
