#!/usr/bin/perl -w
# CleanLog
# 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) = (0,0);
my ($help,$masterhost,$masterport,$masteruser,$masterpassword);

my $result = GetOptions(
	"debug!" => \$debug, "verbose!" => \$verbose, "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
";
    exit ((scalar(@ARGV) < 2)? 1:0);
}

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

my $dbname = $ARGV[0];
my $howold = $ARGV[1];

my $minfo = "dbname=$dbname";
$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));

print "Master connection is $minfo\n" if ($debug);

my $conn = Pg::connectdb($minfo);

my $res = CleanLog($conn, $howold);

exit(1) if $res < 0;

printf STDERR "Deleted %d log records\n", $res if $res > 0;

exit(0);
