#!/usr/bin/env bash

set -e

BUILDDIR="/home/tomas/builds-tmpfs"
DATADIR=/mnt/wd/numa-tests-2/data
PATH_OLD=$PATH

killall -q -9 postgres || true
rm -Rf data

SCALE=2000
PARTITIONS=100
DURATION=60
RUNS=5

export PATH=$BUILDDIR/master/bin:$PATH_OLD

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

mkdir $TS

pg_ctl -D data init > $TS/init.log 2>&1

echo 'shared_buffers = 16GB' >> data/postgresql.conf
echo 'io_method = io_uring' >> data/postgresql.conf
echo 'max_parallel_maintenance_workers = 0' >> data/postgresql.conf
echo 'max_parallel_workers_per_gather = 0' >> data/postgresql.conf
echo 'huge_pages = on' >> data/postgresql.conf
echo 'max_wal_size = 16GB' >> data/postgresql.conf

cp data/postgresql.conf ./

pg_ctl -D data -l pg.log start >> $TS/init.log 2>&1

createdb test >> $TS/init.log 2>&1

pgbench -i -s $SCALE --partitions=$PARTITIONS test >> $TS/init.log 2>&1

pg_ctl -D data -l pg.log stop >> $TS/init.log 2>&1


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

	mkdir $TS/$r

	for b in master numa-0001 numa-0002 numa-0003 numa-0004 numa-0005 numa-0006 numa-0007; do

		export PATH=$BUILDDIR/$b/bin:$PATH_OLD

		for q in count offset; do

			for c in 1 8 32; do

				for numa in off on; do

					if [ "$b" == "master" ] || [ "$b" == "numa-0001" ] || [ "$b" == "numa-0002" ]; then
						if [ "$numa" == "on" ]; then
							continue
						fi
					fi

					cp postgresql.conf data/

					if [ "$numa" == "on" ]; then
						echo "shared_buffers_numa = on" >> data/postgresql.conf
					fi

					pg_ctl -D data -l pg.log start >> $TS/$r/init.log 2>&1

					psql test -c "select * from pg_settings" > $TS/$r/settings-$b-$q-$c-$numa.log 2>&1

					pgbench -n -M prepared -f $q.sql -T $DURATION -l -c $c -j 1 --log-prefix=$TS/$r/log-$b-$q-$c-$numa test > $TS/$r/pgbench-$b-$q-$c-$numa.log 2>&1

					pg_ctl -D data -l pg.log stop >> $TS/$r/init.log 2>&1

					tps=$(grep 'tps = ' $TS/$r/pgbench-$b-$q-$c-$numa.log | awk '{print $3}')

					cat $TS/$r/log-$b-$q-$c-$numa.* | awk '{print $3}' | sort -n > $TS/$r/log-$b-$q-$c-$numa.sorted

					n=$(wc -l $TS/$r/log-$b-$q-$c-$numa.sorted | awk '{print $1}')

					median=$(cat $TS/$r/log-$b-$q-$c-$numa.sorted | head -n $((n/2)) | tail -n 1)

					pct25=$(cat $TS/$r/log-$b-$q-$c-$numa.sorted | head -n $((n/4)) | tail -n 1)
					pct75=$(cat $TS/$r/log-$b-$q-$c-$numa.sorted | head -n $((n*3/4)) | tail -n 1)
					pct95=$(cat $TS/$r/log-$b-$q-$c-$numa.sorted | head -n $((n*95/100)) | tail -n 1)
					pct99=$(cat $TS/$r/log-$b-$q-$c-$numa.sorted | head -n $((n*99/100)) | tail -n 1)

					echo $r $b $q $c $numa $tps $median $pct25 $pct75 $pct95 $pct99 >> $TS/results.csv

				done

			done

		done

	done

done
