#!/usr/bin/env bash

set -e

RUNS=3

killall -9 postgres || true
sleep 1

rm -Rf data

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


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

pg_ctl -D data init
echo 'shared_buffers = 8GB' >> data/postgresql.conf


# size of fact, dim is always 1/10 of fact
for size in 1 10 100; do

	rows_fact=$((size * 1000000))
	rows_dim=$((size * 1000000/10))

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

		for type in integer uuid text; do

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

			pg_ctl -D data -l pg.log start
			createdb test
			cat $type.sql | sed "s/ROWS_FACT/$rows_fact/" | sed "s/ROWS_DIM/$rows_dim/" | psql test
			pg_ctl -D data -l pg.log stop

			for wm in 1024 4096 16384 65536 262144; do

				for pct in 0.05 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 0.95 1.0; do

					for build in master bloom; do

						for bloom in on off; do

							for pw in 0 4; do

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

								opt="";
								if [ "$build" == "bloom" ]; then
									opt="SET enable_hashjoin_bloom = $bloom;";
								fi

								export PATH=/home/tomas/builds/$build/bin:$PATH_OLD
								pg_ctl -D data -l pg.log start

								psql test > tmp.log 2>&1 <<EOF
SET enable_mergejoin = off;
SET enable_nestloop = off;
SET max_parallel_workers_per_gather = $pw;
SET work_mem = $wm;
SET parallel_setup_cost = 0;
SET parallel_tuple_cost = 0;
$opt;
EXPLAIN (ANALYZE, TIMING OFF) SELECT * FROM f JOIN d ON (f.did = d.id) AND d.r < $pct;
EOF

								psql test > explain.log 2>&1 <<EOF
SET enable_mergejoin = off;
SET enable_nestloop = off;
SET max_parallel_workers_per_gather = $pw;
SET work_mem = $wm;
SET parallel_setup_cost = 0;
SET parallel_tuple_cost = 0;
$opt;
EXPLAIN (ANALYZE, VERBOSE, TIMING OFF) SELECT * FROM f JOIN d ON (f.did = d.id) AND d.r < $pct;
EOF

								pg_ctl -D data -l pg.log stop

								t=$(grep 'Execution Time' tmp.log | awk '{print $3}')
								b=$(grep 'Batches:' tmp.log | awk '{print $4}')

								echo "===== run: $r  size: $size  type: $type  wm: $wm  pct: $pct  build: $build  bloom: $bloom  workers: $pw  timing: $t  batches: $b =====" >> explains-$TS.log
								cat explain.log >> explains-$TS.log

								echo $r $size $type $wm $pct $build $bloom $pw $b $t >> results-$TS.csv

							done

						done

					done

				done

			done

			pg_ctl -D data -l pg.log start
			dropdb test
			pg_ctl -D data -l pg.log stop

		done

	done

done
