#! /bin/sh
psql=/usr/pgsql-15/bin/psql
pg_rewind=/usr/pgsql-15/bin/pg_rewind
pg_basebackup=/usr/pgsql-15/bin/pg_basebackup
PG_CTL=/usr/pgsql-15/bin/pg_ctl
DATADIR_BASE=/var/volum/RockyLinux8/15/V4_3_STABLE/src/test/regression/tests/077.invalid_failover_node/testdir
PGSUPERUSER=postgres
MAX_DURATION=60
pgversion=150

main_db_cluster=$1
recovery_node_host_name=$2
DEST_CLUSTER=$3
PORT=$4
recovery_node=$5

pg_rewind_failed="true"

log=$DATADIR_BASE/log/recovery.log
echo >> $log
date >> $log

# Make backup copy of postgresql.conf since pg_rewind/pg_basebackup blindly copies
# $main_db_cluster/postgresql.conf.
cp $DEST_CLUSTER/postgresql.conf /tmp/

pg_rewind_failed="true"
export PGHOST=localhost
if [ $pg_rewind_failed = "true" ];then

echo "source: $main_db_cluster dest: $DEST_CLUSTER" >> $log

rm -fr $DEST_CLUSTER/*
test -d $DEST_CLUSTER || mkdir $DEST_CLUSTER

$pg_basebackup -w -U $PGSUPERUSER -p $PORT -D $DEST_CLUSTER -c fast

fi
cat > $DEST_CLUSTER/myrecovery.conf <<REOF
primary_conninfo      = 'host=localhost port=$PORT user=$PGSUPERUSER application_name=''server$recovery_node'''
recovery_target_timeline='latest'
restore_command = 'cp $DATADIR_BASE/archivedir/`basename $1`/%f "%p" 2> /dev/null'
REOF
cp /tmp/postgresql.conf $DEST_CLUSTER/
touch $DEST_CLUSTER/standby.signal
