#!/bin/bash

RUNDIR=`date +%Y%m%d-%H%M%S`
DURATION=15
RUNS=3

mkdir $RUNDIR

for nrows in 100 1000000 10000; do

	for nparts in 64 1 32 4 16 8; do

		for nindexes in 32 0 16 1 8 4; do

			dropdb test
			createdb test

			# create table and partitions
			psql test -c "create table t (a int, b int, c int, d int) partition by hash (a)"

			for p in `seq 0 $((nparts-1))`; do
				psql test -c "create table t_$p partition of t for values with (modulus $nparts, remainder $p)"
			done

			# insert a couple rows
			psql test -c "insert into t select i, i, i, i from generate_series(1,$nrows) s(i)"

			# create indexes
			for i in `seq 1 $nindexes`; do
				psql test -c "create index idx_$i on t (b)"
			done

			psql test -c "vacuum analyze"
			psql test -c "checkpoint"

			for r in `seq 1 $RUNS`; do

				for c in 1 128 96 16 64 32; do

					echo `date` "RUN: rows $nrows partitions $nparts idexes $nindexes run $r clients $c"

					j=1
					if [ "$c" -ge "8" ]; then
						j=8
					fi

					mkdir -p $RUNDIR/$nrows/$nparts/$nindexes/$r/$c

					./collect-stats.sh $RUNDIR/$nrows/$nparts/$nindexes/$r/$c $DURATION >> collect.log 2>&1 &

					pgbench -n -M prepared -c $c -j $j -f simple.sql -T $DURATION test > $RUNDIR/$nrows/$nparts/$nindexes/$r/$c/pgbench.log 2>&1
					tps=`grep tps $RUNDIR/$nrows/$nparts/$nindexes/$r/$c/pgbench.log | awk '{print $3}'`

					wait $pid

					echo $nrows $nparts $nindexes $r $c $tps >> $RUNDIR/simple.csv

				done

			done

		done

	done

done
