#! /bin/perl

use Cwd;

# This IP address must be a valid and accessible remote address,
# otherwise replication connection will immediately fail with 'No
# route to host', while we want to wait for replication connection to
# complete.
$primary_addr = '192.168.56.1';
$primary_port = 5432;
$fwzone = 'public';
$rootdir = cwd();
$standby_dir = "$rootdir/standby";
$standby_port = 5432;
$standby_logfile= "standby.log";
$rich_rule = "'rule family=\"ipv4\" destination address=\"$primary_addr\" port port=\"$primary_port\" protocol=\"tcp\" drop'";
$add_cmd = "sudo firewall-cmd --zone=$fwzone --add-rich-rule=$rich_rule";
$del_cmd = "sudo firewall-cmd --zone=$fwzone --remove-rich-rule=$rich_rule";

# Remove old entities
system('killall -9 postgres');
system("rm -rf $standby_dir $standby_logfile");

# Setup packet drop 
system($add_cmd) == 0 or die "failed to exec \"$add_cmd\": $!\n";

# Setup a standby.
system("initdb -D $standby_dir -c primary_conninfo='host=$primary_addr port=$primary_port'");
system("touch $standby_dir/standby.signal");

# Start it.
system("pg_ctl start -D $standby_dir -o \"-p $standby_port\" -l standby.log");
sleep 1;

# Try promoting standby, waiting for 10 seconds.
system("pg_ctl promote -t 10 -D $standby_dir");

# Stop servers
system("pg_ctl stop -m i -D $standby_dir");

# Remove packet-drop setting
system($del_cmd) == 0 or die "failed to exec \"$del_cmd\": $!\n";
