#!/bin/bash
# Test pg_rewind leaks

MASTER_DATA=$HOME/data/5432
STANDBY_DATA=$HOME/data/5433
PG_SOURCE=$HOME/postgres

# Create cluster
rm -r $MASTER_DATA $STANDBY_DATA
initdb -D $MASTER_DATA > /dev/null 2>&1
cat >> $MASTER_DATA/postgresql.conf <<EOF
wal_level = hot_standby
wal_log_hints = on
max_wal_senders = 10
hot_standby = on
wal_keep_segments = 25
EOF
cat >> $MASTER_DATA/pg_hba.conf <<EOF
host replication $USER 127.0.0.1/32 trust
host replication $USER ::1/128 trust
local replication $USER trust
EOF
pg_ctl start -s -w -D $MASTER_DATA
createdb $USER > /dev/null 2>&1
pg_basebackup -D $STANDBY_DATA -p 5432 -R > /dev/null 2>&1
cat >> $STANDBY_DATA/postgresql.conf <<EOF
port = 5433
EOF
pg_ctl start -s -w -D $STANDBY_DATA

# Create a bunch of objects able to trigger a failure
psql -Atq -c 'CREATE TABLE aa (a int)'
for i in {1..10}; do
	psql -Atq -c 'INSERT INTO aa VALUES (generate_series(1,1000))'
done
sleep 2 # Let room to replay

# Time to fork
pg_ctl promote -s -D $STANDBY_DATA -w
sleep 2
for i in {1..10}; do
	psql -Atq -c 'INSERT INTO aa VALUES (generate_series(1,1000))'
	psql -Atq -c 'INSERT INTO aa VALUES (generate_series(1,2000))' -p 5433
done
sleep 2

pg_ctl stop -s -D $MASTER_DATA

valgrind --trace-children=yes \
		 --suppressions=$PG_SOURCE/src/tools/valgrind.supp \
		 --dsymutil=yes \
		 --leak-check=full \
		 --track-origins=yes \
		 --read-var-info=yes \
		 pg_rewind --source-server="port=5433" --target-pgdata=$MASTER_DATA

pg_ctl stop -s -D $STANDBY_DATA
