# Test standby with restarting primary
use strict;
use warnings;

use PostgreSQL::Test::Cluster;
use PostgreSQL::Test::Utils;
use Test::More tests => 1;

my $node_primary = PostgreSQL::Test::Cluster->new('primary');
$node_primary->init(allows_streaming => 1, auth_extra => [ '--create-role', 'repl_role' ]);

$node_primary->append_conf('postgresql.conf', "
max_connections = 100
fsync = off
log_statement = 'none'
wal_keep_size = 2000
");
$node_primary->start;
$node_primary->safe_psql('postgres', "create table tbl(id int, t1 text);");

my $backup_name = 'initial_backup';
$node_primary->backup($backup_name);

my $node_standby = PostgreSQL::Test::Cluster->new('standby');
$node_standby->init_from_backup($node_primary, $backup_name, has_streaming => 1);
$node_standby->append_conf('postgresql.conf', "
fsync = off
");

$node_standby->start;

open(FH, '>', "pgb.sql") or die $!;
print FH <<'EOF';
  insert into tbl (id, t1) select g, repeat('x', 500) from generate_series(1, 1000) g;
  truncate tbl;
EOF
close(FH);

my $pgbench;
my ($pgb_stdin, $pgb_stdout, $pgb_stderr) = ('', '', '');
my $restarts = 0;

while ($restarts < 100) {
    my $standby_state = $node_standby->safe_psql('postgres', 'SELECT 1');
    if ($standby_state != 1) { diag("Standby check failed."); last; }

    $restarts++;
    diag("Restarting primary instance ($restarts)");
    $node_primary->stop();
    $pgbench and $pgbench->finish();
    $node_primary->start();

    $pgbench = IPC::Run::start(
        ['pgbench', '--no-vacuum', '--file=pgb.sql', '--time=60', '--client=5', '--jobs=5',  $node_primary->connstr('postgres')],
        \$pgb_stdin, \$pgb_stdout, \$pgb_stderr);
    sleep(2);
}

$pgbench->finish();

ok(1, "ok");
done_testing();
