#!/bin/bash

DESTDIR="/home/melih-desktop/code/build/"
TESTDIR="/home/melih-desktop/pqcomm_test"

test_cases=(
"100 100 1000000"		# only 100 bytes	
"1024 10240 1000000"    # 1Kb and 10Kb 
"1024 1048576 1000"		# 1Kb and 1Mb 
"1048576 1048576 1000"	# all 1Mb
)

branches=(
"master" 
"pqcomm_buf"
"pqcomm_no_buffer"
)


buffer_sizes=(
1400
2048
4096
8192
16384
32768
)

insert_rows(){
	psql -d postgres -p 5432 -c "
	DO \$\$
	DECLARE
	    counter INT;
	BEGIN
	    FOR counter IN 1..$3 LOOP
	        IF counter % 2 = 1 THEN
	            INSERT INTO test_table VALUES (repeat('a', $1)::text);
	        ELSE
	            INSERT INTO test_table VALUES (repeat('b', $2)::text);
	        END IF;
	    END LOOP;
	END \$\$;
	"
}


for branch in "${branches[@]}"
do

git checkout $branch
	rm -rf $DESTDIR

	meson setup --buildtype debug -Dcassert=true --prefix="$DESTDIR/usr/local/pgsql" $DESTDIR && \
	ninja -C $DESTDIR && \
	meson install --quiet -C $DESTDIR

	for case in "${test_cases[@]}" 
	do
		pkill postgres
		rm -rf $TESTDIR/test
		initdb -D $TESTDIR/test
		pg_ctl -D $TESTDIR/test -l $TESTDIR/logfile start

		psql -d postgres -p 5432 -c "CREATE TABLE test_table(data text not null);"
		insert_rows $case

		for buf_size in "${buffer_sizes[@]}"
		do

			echo "pq_send_buffer_size = ${buf_size}" >> $TESTDIR/test/postgresql.conf
			pg_ctl -D $TESTDIR/test -l $TESTDIR/logfile restart


			elapsed_time=0
			for a in {1..3}
			do
				echo "Run ${a}"

				echo 3 | sudo tee /proc/sys/vm/drop_caches

				pg_ctl -D $TESTDIR/test -l $TESTDIR/logfile restart

				start_time=$(date +%s%N)
				psql -d postgres -p 5432 -c "COPY test_table TO STDOUT;" 1> /dev/null
				end_time=$(date +%s%N)

				elapsed_time=$(( (end_time - start_time) + elapsed_time))

			done

			avg_elapsed_time_in_ms=$((elapsed_time / 3 / 1000000))
			echo -e "${branch}-${case}-${buf_size} : ${avg_elapsed_time_in_ms}" >> $TESTDIR/results_tiny.txt

		done

		pg_ctl -D $TESTDIR/test -l $TESTDIR/logfile stop
	done
done
