#!/usr/bin/bash

set -e

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

rm -f builds.txt
for build in master master-1 master-2 master-4 master-8 master-16; do
	echo $build >> builds.txt
done

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 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 $(shuf builds.txt); do
					#for build in master master-1 master-2 master-4 master-8 master-16; 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
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 $perc $build $d $pages_remain $pages_scanned $avg_read $avg_write" >> results.csv

					done

				done

		done

	done

done
