PG15_PGDATA="/home/masahiko/pgsql/15.s/data"
PG16_PGDATA="/home/masahiko/pgsql/16.s/data"
PG15_BIN="/home/masahiko/pgsql/15.s/bin"
PG16_BIN="/home/masahiko/pgsql/16.s/bin"

ROWS=$((100 * 1000 * 1000))
CLIENTS="1 2 4 8 16 32 64 128 256"

${PG15_BIN}/pg_ctl stop -D ${PG15_PGDATA} -mi
${PG16_BIN}/pg_ctl stop -D ${PG16_PGDATA} -mi
rm -rf $PG15_PGDATA $PG16_PGDATA

echo "initializing clusters ..."
${PG15_BIN}/initdb -D $PG15_PGDATA -E UTF8 --no-locale
${PG16_BIN}/initdb -D $PG16_PGDATA -E UTF8 --no-locale

cat <<EOF >> ${PG15_PGDATA}/postgresql.conf
port = 5515
max_wal_size = 50GB
shared_buffers = 20GB
max_connections = 500
EOF
cat <<EOF >> ${PG16_PGDATA}/postgresql.conf
port = 5516
max_wal_size = 50GB
shared_buffers = 20GB
max_connections = 500
EOF

if [ "$1" != "skip_file_init" ]; then
    echo "prepare load files..."
    ${PG16_BIN}/pg_ctl start -D ${PG16_PGDATA}
    for c in $CLIENTS
    do
	rm -f /tmp/tmp_${c}.data
	${PG16_BIN}/psql -d postgres -p 5516 -X -c "copy (select generate_series(1, $ROWS / $c)) to '/tmp/tmp_${c}.data'"
    done
    ${PG16_BIN}/pg_ctl stop -D ${PG16_PGDATA}
fi

echo "start benchmark ..."
#for version in PG15 PG16
for version in PG16
do
    PSQL=""
    if [ "$version" == "PG15" ]; then
	PSQL="${PG15_BIN}/psql -p 5515 -d postgres"
	${PG15_BIN}/pg_ctl start -D ${PG15_PGDATA}
    else
	PSQL="${PG16_BIN}/psql -p 5516 -d postgres"
	${PG16_BIN}/pg_ctl start -D ${PG16_PGDATA}
    fi

    ${PSQL} -c "create unlogged table test (c int) with (autovacuum_enabled = off)"

    for c in $CLIENTS
    do
	${PSQL} -c "truncate test" > /dev/null 2>&1

	chileren=()
	start=`date +%s.%3N`
	for i in `seq 1 $c`
	do
	    ${PSQL} -c "copy test from '/tmp/tmp_${c}.data'" > /dev/null 2>&1 &
	    children+=($!)
	done
	wait ${children[@]}
	end=`date +%s.%3N`

	exec_time=$(echo "scale=3; $end - $start" | bc)
	echo "$version: nclients = $c, execution time = $exec_time"
    done

    if [ "$version" == "PG15" ]; then
	${PG15_BIN}/pg_ctl stop -D ${PG15_PGDATA} -mi
    else
	${PG16_BIN}/pg_ctl stop -D ${PG16_PGDATA} -mi
    fi
done
