#!/usr/bin/bash

PATH_OLD=$PATH

killall -9 postgres || true
sleep 1

rm -f clients.list
for c in 1 8 16 32 64 128; do
	echo $c >> clients.list
done

for num_partitions in 100 10 0 1000; do

	for branch in pruning master; do

		for plan_mode in force_custom_plan force_generic_plan auto; do

			for num_locks in 16 64 256 1024 4096; do

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

				rm -Rf /mnt/pgdata/data-pruning
				pg_ctl -D /mnt/pgdata/data-pruning init >> logs/init-$num_partitions-$branch-$plan_mode-$num_locks.log 2>&1

				echo "plan_cache_mode = '$plan_mode'" >> /mnt/pgdata/data-pruning/postgresql.conf
				echo "max_locks_per_transaction = $num_locks" >> /mnt/pgdata/data-pruning/postgresql.conf
				echo "max_connections = 10000" >> /mnt/pgdata/data-pruning/postgresql.conf

				pg_ctl -D /mnt/pgdata/data-pruning -l logs/pg-$num_partitions-$branch-$plan_mode-$num_locks.log start
				createdb test

				pgbench -i -s 1 --partitions=$num_partitions test >> logs/pgbench-init-$num_partitions-$branch-$plan_mode-$num_locks.log 2>&1

				psql test -c "vacuum analyze"

				for query_mode in simple prepared; do

					for r in $(seq 1 10); do

						for num_clients in $(shuf clients.list); do

							pgbench -S -n -M $query_mode -c $num_clients -j $num_clients -P 1 -T 15 test > logs/pgbench-$num_partitions-$branch-$plan_mode-$num_locks-$query_mode-$r-$num_clients.log 2>&1

							tps=$(grep 'tps = ' logs/pgbench-$num_partitions-$branch-$plan_mode-$num_locks-$query_mode-$r-$num_clients.log | tail -n 1 | awk '{print $3}')

							echo $num_partitions $plan_mode $num_locks $branch $query_mode $r $num_clients $tps >> results.csv

						done

					done

				done

				pg_ctl -D /mnt/pgdata/data-pruning stop

			done

		done

	done

done
