use strict;
use warnings;

use PostgreSQL::Test::Cluster;
use PostgreSQL::Test::Utils;
use Test::More;

my $backup_name = "replica";

my $node_primary = PostgreSQL::Test::Cluster->new('primary');
$node_primary->init(allows_streaming => 1);
$node_primary->append_conf('postgresql.conf', 'fsync = on');
# $node_primary->append_conf('postgresql.conf', 'log_min_messages=debug1');
$node_primary->start;

$node_primary->backup($backup_name);

# Fill WAL a little bit
$node_primary->safe_psql(
	'postgres', qq[
CREATE TABLE test(a int, b int);
INSERT INTO test SELECT s FROM generate_series(1, 10000) AS s;
]);

# Promote the primary node up to TLI 2
$node_primary->stop('immediate');
$node_primary->set_standby_mode;

$node_primary->start;
$node_primary->promote;

# Fill WAL a little bit again
$node_primary->safe_psql(
	'postgres', qq[
INSERT INTO test SELECT s FROM generate_series(1, 10000) AS s;
]);

my $node_standby = PostgreSQL::Test::Cluster->new($backup_name);
$node_standby->init_from_backup($node_primary, $backup_name,
	has_streaming => 1);

$node_standby->start;
sleep(5);
$node_standby->promote;

# $node_standby->start;
# If you try to start the node again you'll get startup PANIC again:
# startup LOG:  invalid magic number 0000 in WAL segment 000000020000000000000003, LSN 0/03020000, offset 131072
# startup FATAL:  according to history file, WAL location 0/0301FFD0 belongs to timeline 1, but previous recovered WAL file came from timeline 2

ok(1);
done_testing();
