#
# Topology:
#   P (primary)  ---->  S1 (standby, will be promoted)
#                     \ S2 (standby under test)
#

use strict;
use warnings FATAL => 'all';
use PostgreSQL::Test::Cluster;
use PostgreSQL::Test::Utils;
use Test::More;

# Initialize primary node
my $node_primary = PostgreSQL::Test::Cluster->new('primary');
$node_primary->init(allows_streaming => 1);
$node_primary->start;

# Create some content on primary
$node_primary->safe_psql('postgres',
	"CREATE TABLE test_table(a int, b text)");
$node_primary->safe_psql('postgres',
	"INSERT INTO test_table SELECT g, 'seed' FROM generate_series(1,500) g");
# $node_primary->safe_psql('postgres', "SELECT pg_switch_wal()");

# Take backup
my $backup_name = 'my_backup';
$node_primary->backup($backup_name);

# Create standby S1 linking to primary
my $node_standby_1 = PostgreSQL::Test::Cluster->new('standby1');
$node_standby_1->init_from_backup($node_primary, $backup_name,
    has_streaming => 1);
$node_standby_1->append_conf('postgresql.conf', qq(
log_min_messages = debug1
autovacuum = off
wal_retrieve_retry_interval = 10s
));

# Create standby S2 linking to primary
my $node_standby_2 = PostgreSQL::Test::Cluster->new('standby2');
$node_standby_2->init_from_backup($node_primary, $backup_name,
    has_streaming => 1);
$node_standby_2->append_conf('postgresql.conf', qq(
log_min_messages = debug1
autovacuum = off
wal_retrieve_retry_interval = 10s
));

$node_standby_1->start;

$node_standby_1->poll_query_until('postgres', "SELECT pg_is_in_recovery() = 't'")
    or die "Timed out while waiting for S1 to be in recovery";

$node_standby_2->start;
$node_standby_2->poll_query_until('postgres', "SELECT pg_is_in_recovery() = 't'")
    or die "Timed out while waiting for S2 to be in recovery";

# Stop S2
$node_standby_2->stop('fast');

# Stop primary
$node_primary->stop('fast');

# Promote S1
$node_standby_1->promote;

$node_standby_1->poll_query_until('postgres', "SELECT NOT pg_is_in_recovery();")
    or die "Timed out while waiting for promotion";

# Repoint S2 to follow S1
my $connstr_1 = $node_standby_1->connstr;
$node_standby_2->append_conf(
    'postgresql.conf', qq(
primary_conninfo='$connstr_1'
));
$node_standby_2->start;

# Check the logs, WAL receiver should not have been stopped.
ok( !$node_standby_2->log_contains(
	"FATAL: .* terminating walreceiver process due to administrator command"),
	'WAL receiver should not be stopped during waiting state');

done_testing();
