#!/bin/sh
# - scale_factor
# - runtime
# - nr_task
# - transcations
# - worker_threads
# - latency_limit
# - max_wal_size
# - wal_compression
# - checkpoint_timeout
# - checkpoint_completion_target

. $LKP_SRC/lib/reproduce-log.sh
. $LKP_SRC/lib/env.sh

postgres_run()
{
	sudo -u postgres $exec_prefix "$@"
}

postgres_run_log()
{
	log_cmd sudo -u postgres $exec_prefix "$@"
}

init_postgresql()
{
	grep -q postgres /etc/passwd && return

	useradd --home-dir /var/lib/postgresql --no-create-home --no-user-group --gid nogroup --system postgres
	data_dir=${mount_points%% *}/var/lib/postgresql/data
	mkdir -p "$data_dir"
	chown postgres "$data_dir"

	bin_dir=/usr/lib/postgresql/*/bin

	postgres_run $bin_dir/initdb  -D "$data_dir" 2>&1
	postgresql_conf_file="$data_dir"/postgresql.conf
	run_dir=/var/run/postgresql
	mkdir -p "$run_dir"
	chown postgres "$run_dir"
	postgres_run $bin_dir/pg_ctl -D "$data_dir" start
}

postgresql_conf_file=$(find /etc/postgresql -name postgresql.conf | head -1)

init_postgresql

[ -n "$max_wal_size" ] &&
	log_eval "echo 'max_wal_size = $max_wal_size' >> $postgresql_conf_file"

[ -n "$scale_factor" ] && init_opts="-s $scale_factor"

postgres_run dropdb pgbench_test > /dev/null 2>&1
postgres_run_log createdb pgbench_test
postgres_run_log pgbench -i $init_opts 2>&1

if [ -n "$runtime" ]; then
	run_opts="-T $runtime"
elif [ -n "$transcations" ]; then
	run_opts="-t $transcations"
else
	run_opts="-T 300"
fi

[ -n "$nr_task" ] && run_opts="$run_opts -c $nr_task"
[ -n "$worker_threads" ] && run_opts="$run_opts -j $worker_threads"
[ -n "$latency_limit" ] && run_opts="$run_opts -L $latency_limit"

cat > "$TMP_RESULT_ROOT"/run.pgbench <<EOF
log_cmd sudo -u postgres $exec_prefix pgbench -n $run_opts
EOF
