#!/bin/sh

PGPATH=.

export PGDATABASE=postgres

set -e

$PGPATH/bin/initdb -D data-master

cat >> data-master/postgresql.conf <<EOF
#added by setup_hot_standby.sh
max_prepared_transactions = 5
max_wal_senders = 5
#max_replication_slots = 5
wal_level = hot_standby
wal_keep_segments = 20
port=5434
#archive_mode=on
#archive_command='test ! -f $PWD/walarchive/%f && cp %p $PWD/walarchive/%f'
wal_log_hints=on
EOF

echo "local   replication     heikki         trust" >> data-master/pg_hba.conf

$PGPATH/bin/pg_ctl -w -D data-master start


#Node -1 (master):
#Step-1

$PGPATH/bin/psql -p 5434 -c "Create table t1(c1 int, c2 char(500)) with (fillfactor=10);"
$PGPATH/bin/psql -p 5434 -c "insert into  t1 values(generate_series(1,110),'aaaa');"

#Stop Node-1 (pg_ctl stop ..)
$PGPATH/bin/pg_ctl stop -w -D data-master

#Step-2
#Copy manually the data-directory (it contains WAL log as well)
#to new location say Database1
cp -a data-master data-standby

#Node-2 (standby)
#Step-3
#Change settings to make it stand-by (recovery.conf and change
#postgresql.conf)
#Start Node and verify all data exists.
cat >> data-standby/recovery.conf <<EOF
standby_mode=on
EOF
cat >> data-standby/postgresql.conf <<EOF
port=5433
hot_standby=on
log_line_prefix='S '
EOF

$PGPATH/bin/pg_ctl -w -D data-standby start


#Step-4
#use pg_ctl promote to make Node-2 as master
$PGPATH/bin/pg_ctl -w -D data-standby promote

#Missing step: restart Node-1
$PGPATH/bin/pg_ctl -w -D data-master start

#Step-5
#Start Node-1
#insert few more records
$PGPATH/bin/psql -p 5434 -c "insert into  t1 values(generate_series(110,115),'aaaa');"

#Step-6
#Node-2
#Now insert one more records in table t1
$PGPATH/bin/psql -p 5433 -c "insert into  t1 values(116,'aaaa');"

#Stop both the nodes.
$PGPATH/bin/pg_ctl -D data-master stop
$PGPATH/bin/pg_ctl -D data-standby stop

#Now if I run pg_rewind on old-master(Node-1), it will lead to above error.

$PGPATH/bin/pg_rewind --source-pgdata=data-standby --target-pgdata=data-master --dry-run


