#!/usr/bin/env bash

set -e

PATH_OLD=$PATH
RUNS=1
DURATION=10

killall -9 postgres || true
sleep 1

rm -Rf data

TS=$(date +%Y%m%d-%H%M%S)

mkdir $TS

export PATH=/home/tomas/builds/master/bin:$PATH_OLD

pg_ctl -D data init
pg_ctl -D data -l $TS/pg.log start

createdb test
psql test < init.sql

pg_ctl -D data -l $TS/pg.log stop


echo "run dims clients geqo build starjoin limit tps" > $TS/starjoins.csv

for r in $(seq 1 $RUNS); do

        #for dims in 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1; do
	for dims in 15 13 11 9 7 5 3 1; do

		#for c in 1 8; do
		for c in 1; do

			for geqo in on off; do

				for build in master starjoins; do

					export PATH=/home/tomas/builds/$build/bin:$PATH_OLD

					for starjoin in off on; do

						if [ "$build" == "master" ] && [ "$starjoin" == "on" ]; then
							continue;
						fi

						for limit in 1 8 16; do

							pg_ctl -D data -l $TS/pg.log start

							if [ "$build" == "starjoins" ]; then
								psql test -c "alter user \"tomas\" set enable_starjoin_ordering = $starjoin" >> $TS/debug.log 2>&1
							fi

							psql test -c "alter user \"tomas\" set join_collapse_limit = $limit" >> $TS/debug.log 2>&1
							psql test -c "alter user \"tomas\" set geqo = $geqo" >> $TS/debug.log 2>&1

							pgbench -n -c $c -j $c -f star-$dims.sql -T $DURATION -P 1 test > $TS/$starjoin-$limit-$dims-$r.log 2>&1

							tps=$(grep 'tps = ' $TS/$starjoin-$limit-$dims-$r.log | awk '{print $3}')

							echo $r $dims $c $geqo $build $starjoin $limit $tps >> $TS/starjoins.csv

							psql test -c "alter user \"tomas\" reset join_collapse_limit"
							psql test -c "alter user \"tomas\" reset geqo"

							if [ "$build" == "starjoins" ]; then
								psql test -c "alter user \"tomas\" reset enable_starjoin_ordering"
							fi

							pg_ctl -D data -l $TS/pg.log stop

						done

					done

				done

                        done

                done

        done

done
