#!/usr/bin/perl -w
# GetSyncID
# 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 Pg;
use Getopt::Long;
use RServ;

$| = 1;

my ($debug,$verbose) = (0,1);
my ($help,$slavehost,$slaveport,$slaveuser,$slavepassword);

my $result = GetOptions(
	"debug!" => \$debug, "verbose!" => \$verbose, "help" => \$help,
	"slavehost=s" => \$slavehost, "slaveport=i" => \$slaveport,
	"slaveuser=s" => \$slaveuser, "slavepassword=s" => \$slavepassword,
	);

if (defined($help) || (scalar(@ARGV) < 1)) {
    print "Usage: $0 [options] slavedb table column
Options:
	--slavehost=hostname --slaveport=port
	--slaveuser=username --slavepassword=string
";
    exit ((scalar(@ARGV) < 1)? 1:0);
}

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

my $dbname = $ARGV[0];

my $sinfo = "dbname=$dbname";
$sinfo = "$sinfo host=$slavehost" if (defined($slavehost));
$sinfo = "$sinfo port=$slaveport" if (defined($slaveport));
$sinfo = "$sinfo user=$slaveuser" if (defined($slaveuser));
$sinfo = "$sinfo password=$slavepassword" if (defined($slavepassword));

print("Connecting to '$sinfo'\n") if ($debug || $verbose);
my $conn = Pg::connectdb($sinfo);

my $res = GetSyncID($conn);

die "ERROR\n" if $res < 0;

if (! defined $res)
{
    printf STDERR "No SyncID found\n";
}
else
{
    print("Last SyncID applied: ") if ($verbose);
    printf "%d", $res;
    print("\n") if ($verbose);
}

exit(0);
