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

program_help_ok('pg_createsubscriber');
program_version_ok('pg_createsubscriber');
program_options_handling_ok('pg_createsubscriber');

# primary
my $primary = PostgreSQL::Test::Cluster->new('primary');
my $primary_connstr = $primary->connstr;
$primary->init(allows_streaming => 'logical');

$primary->start();

$primary->safe_psql('postgres', "CREATE DATABASE bench");
$primary->safe_psql('bench',
	"SELECT pg_create_physical_replication_slot('physical_slot')");

$primary->backup('primary_backup');

# physical replica
my $replica = PostgreSQL::Test::Cluster->new('replica');
$replica->init_from_backup($primary, 'primary_backup', has_streaming => 1);
my $logical_pgdata = $replica->data_dir;

$replica->append_conf(
	'postgresql.conf', qq[
primary_slot_name = 'physical_slot'
primary_conninfo = '$primary_connstr dbname=bench'
hot_standby_feedback = on
restore_command = 'cp $logical_pgdata/pg_wal/%f %p'
]);

$replica->set_standby_mode();
$replica->start();
$replica->stop();

# converting physical replica to logical
command_ok(
	[
		'pg_createsubscriber', '--verbose',
		'-D', $replica->data_dir,
		'--database', 'bench',
		'--publisher-server', $primary_connstr,
		'--replication-slot', 'pg_log_slot',
		'--publication', 'pg_publication',
		'--subscription', 'pg_subscription'
	],
	'convert physical replica to logical'
);

$replica->start();
$replica->stop();

$replica->set_recovery_mode();

is($replica->start(), 1, "logical replica performs recovery");

done_testing();