#!/usr/bin/perl -w
# MasterSync
# Vadim Mikheev, (c) 2000, PostgreSQL Inc.

eval '(exit $?0)' && eval 'exec perl -S $0 ${1+"$@"}'
    & eval 'exec perl -S $0 $argv:q'
    if 0;

BEGIN {
	my $basedir = $0; $basedir =~ s#/[^/]+$##;
	unshift(@INC, "$basedir/../share");
}

use strict;
use Getopt::Long;
use RServ;

$| = 1;

my ($debug,$verbose,$quiet) = (0,0,0);
my ($help,$masterhost,$masterport,$masteruser,$masterpassword);

my $result = GetOptions(
	"debug!" => \$debug, "verbose!" => \$verbose,
	"quiet!" => \$quiet, "help" => \$help,
	"masterhost=s" => \$masterhost, "masterport=i" => \$masterport,
	"masteruser=s" => \$masteruser, "masterpassword=s" => \$masterpassword,
	);

if (defined($help) || (scalar(@ARGV) < 2) || ($ARGV[1] !~ /^\d+$/)) {
    print "Usage: $0 [options] masterdb syncid
Options:
	--masterhost=hostname --masterport=port
	--masteruser=username --masterpassword=string
	--quiet
";
    exit ((scalar(@ARGV) < 2)? 1:0);
}

$RServ::quiet = !$verbose;
if ($debug) {
	$RServ::quiet = 0;
	no warnings 'vars';
	$RServ::debug = $debug;
}

my $master = $ARGV[0] || "master";
my $server = 0;
my $syncid = $ARGV[1] || die "SyncID not specified";

my $minfo = "dbname=$master";
$minfo = "$minfo host=$masterhost" if (defined($masterhost));
$minfo = "$minfo port=$masterport" if (defined($masterport));
$minfo = "$minfo user=$masteruser" if (defined($masteruser));
$minfo = "$minfo password=$masterpassword" if (defined($masterpassword));

my $conn = Pg::connectdb($minfo);
if ($conn->status != Pg::PGRES_CONNECTION_OK) {
    print STDERR "Failed opening $minfo\n";
    exit 1;
}

my $res = SyncSyncID($conn, $server, $syncid);

if ($res == 0)
{
    printf STDERR "SyncID updated on $master\n" if ($verbose);
    exit(0);
}

printf STDERR "ERROR\n" unless ($quiet);
exit(1);
