#! /bin/sh
# Execute command by failover.
# special values:  %d = node id
#                  %h = host name
#                  %p = port number
#                  %D = database cluster path
#                  %m = new main node id
#                  %M = old main node id
#                  %H = new main node host name
#                  %P = old primary node id
#                  %R = new main database cluster path
#                  %r = new main port number
#                  %% = '%' character
failed_node_id=$1
failed_host_name=$2
failed_port=$3
failed_db_cluster=$4
new_main_id=$5
new_main_host_name=$6
old_main_id=$7
old_primary_node_id=$8
new_main_port_number=$9
new_main_db_cluster=${10}
mydir=/var/volum/RockyLinux10/17/master/src/test/regression/tests/038.pcp_commands/testdir
log=$mydir/log/failover.log
pg_ctl=/usr/pgsql-17/bin/pg_ctl
PCP_PORT=11001
pgversion=170
export PCPPASSFILE=/var/volum/RockyLinux10/17/master/src/test/regression/tests/038.pcp_commands/testdir/pcppass
PGPOOL_BIN=/var/volum/RockyLinux10/17/master/src/test/regression/temp/installed/bin

date >> $log
echo "failover script started for node: $failed_node_id" >> $log
echo "failed_node_id: $failed_node_id failed_host_name: $failed_host_name failed_port: $failed_port" >> $log
echo "failed_db_cluster: $failed_db_cluster new_main_id: $new_main_id old_main_id: $old_main_id" >> $log
echo "new_main_host_name: $new_main_host_name old_primary_node_id: $old_primary_node_id" >> $log
echo "new_main_port_number: $new_main_port_number new_main_db_cluster: $new_main_db_cluster" >> $log

# check if all node is down
if [ $new_main_id = "-1" ];then
    echo "no new main node is available" >>$log
    exit 0
fi

if [ a"$failed_node_id" = a"$old_primary_node_id" -o a"$old_primary_node_id" = a"-1" ];then	# main node failed
 	new_primary_db_cluster=${mydir}/data"$new_main_id"
	echo $pg_ctl -D $new_primary_db_cluster promote >>$log	# let standby take over
	$pg_ctl -D $new_primary_db_cluster promote >>$log	# let standby take over
	sleep 2
	echo psql -p $new_main_port_number -c "CHECKPOINT" postgres
	psql -p $new_main_port_number -c "CHECKPOINT" postgres
fi
date >> $log
echo "failover script ended" >> $log
