#!/usr/bin/bash

OUTDIR=$1
DATADIR=/mnt/pgdata/data-primary

pg_ctl -D $DATADIR init

echo 'wal_level = logical' >> $DATADIR/postgresql.conf 2>&1
echo "log_line_prefix = '%n %m [%p] [%b:%a] [%c:%l] [%s] [%v/%x] '" >> $DATADIR/postgresql.conf 2>&1
echo "log_min_duration_statement = 0" >> $DATADIR/postgresql.conf 2>&1

pg_ctl -D $DATADIR -l $OUTDIR/pg-primary.log start

# small test
createdb test
pgbench -i -s 10 test

sleep=10
m=fast
s=enabled

# 100 loops of the primary restarts
for r in $(seq 1 100); do

	# run pgbench in the background
	echo `date` "pgbench"
	pgbench -c 4 -P 1 -T 3600 test >> $OUTDIR/pgbench.log 2>&1 &

	# sleep for a bit
	x=$((RANDOM % sleep + 1))
	echo `date` "sleeping for $x seconds"
	sleep $x

	# start the checksums change
	if [ "$s" == "disabled" ]; then
		psql test -c "select pg_enable_data_checksums()"
		s="enabled"
	else
		psql test -c "select pg_disable_data_checksums()"
		s="disabled"
	fi

	# sleep for a bit
	x=$((RANDOM % sleep + 1))
	echo `date` "sleeping for $x seconds"
	sleep $x

	# stop the primary in some way
	m=$((RANDOM % 2))

	if [ "$m" == "0" ]; then
		pg_ctl -D $DATADIR -m immediate stop
	else
		pg_ctl -D $DATADIR -m fast stop
	fi

	# start the primary again
	echo `date` "start primary"
	pg_ctl -D $DATADIR -l $OUTDIR/pg-primary.log start

	# wait for the checksums to get enabled/disabled

	echo `date` "waiting for checksums to change in the instance"
	while /bin/true; do

		c=$(psql -t -A test -c "SELECT setting FROM pg_catalog.pg_settings WHERE name = 'data_checksums'")

		if [ "$s" == "enabled" ] && [ "$c" == "on" ]; then
			break;
		elif [ "$s" == "disabled" ] && [ "$c" == "off" ]; then
			break;
		fi

		echo `date` "checksum state: $c (sleeping)"
		sleep 1

	done

	# kill the instance for fun
	pg_ctl -D $DATADIR -m immediate stop

	if [ "$s" == "enabled" ]; then
		pg_checksums -c $DATADIR
	fi

	pg_ctl -D $DATADIR -l $OUTDIR/pg-primary.log start

done

