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

$| = 1;

#my ($debug,$verbose) = (0,0);
my ($help,$masterhost,$masterport,$masteruser,$masterpassword,
	$slavehost,$slaveport,$slaveuser,$slavepassword);
my $snapshot = ".__Snapshot";
my $multimaster = 0;

my $result = GetOptions(
	"debug!" => \$debug, "verbose!" => \$verbose, "help" => \$help,
	"masterhost=s" => \$masterhost, "masterport=i" => \$masterport,
	"masteruser=s" => \$masteruser, "masterpassword=s" => \$masterpassword,
	"slavehost=s" => \$slavehost, "slaveport=i" => \$slaveport,
	"slaveuser=s" => \$slaveuser, "slavepassword=s" => \$slavepassword,
	"snapshot=s" => \$snapshot,
	"multimaster" => \$multimaster,
	);

if (defined($help) || (scalar(@ARGV) < 2)) {
    print "Usage: $0 [options] masterdb slavedb
Options:
	--masterhost=hostname --masterport=port
	--masteruser=username --masterpassword=string
	--snapshot=snapshot
	[--multimaster]
";
    exit ((scalar(@ARGV) < 2)? 1:0);
}

$snapshot .= '.' . $$;

$RServ::quiet = !$verbose;
#if ($debug) {
#print "## q:$RServ::quiet v:$RServ::verbose d:$RServ::debug\n";
#	$RServ::quiet = 0;
#	no warnings 'vars';
#	$RServ::debug = $debug;
#print "## q:$RServ::quiet v:$RServ::verbose d:$RServ::debug\n";
#}

my $master = $ARGV[0] || "master";
my $slave = $ARGV[1] || "slave";
my $tables = $#ARGV < 2 ? undef : { map {($_, undef)} @ARGV[2..$#ARGV] };

# first, let's check if a instance is alrealy running

my $str = $master;
$str .= '@'.$masterhost if (defined($masterhost));
$str .= ':'.$slave;
$str .= '@'.$slavehost if (defined($slavehost));
my $fname = "/tmp/.lock_rserv-$str";
if (-e $fname) {
	open(PID,$fname) || die "can't open pid file '$fname'";
	my $pid = <PID>; chomp($pid);
	close(PID);
	open(PS,"ps ax |") || die "can't start ps to check for running rServ with pid $pid\n";
	my $is_running = 0;
	while(<PS>) {
		chomp;
		$is_running = 1 if (/^\s*$pid\s/);
	}
	close(PS);
	if ($is_running) {
		print STDERR "rServ [$pid] is already running for $str. Remove $fname to override this.\n";
		exit(1);
	} else {
		print STDERR "found stale pid file, but no running rServ [$pid], overriding.\n";
	}
}
open ARQ, ">$fname" || die "Cannot open $fname: $!\n";
print ARQ "$$\n";
close ARQ;

$SIG{__DIE__} = \&mydie;
sub mydie {
	unlink $fname;
	print @_;
	exit 1;
}

my $minfo = MkInfo($master,$masterhost,$masterport,$masteruser,$masterpassword);
my $sinfo = MkInfo($slave,$slavehost,$slaveport,$slaveuser,$slavepassword);

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

my $mconn = Connect($minfo);
my $sconn = Connect($sinfo);

$slavehost = 'localhost' if (! $slavehost);
$masterhost = 'localhost' if (! $masterhost);

my $slaveId = GetServerId($mconn, $slave, $slavehost);

die "\n>>>>>>>>>>>>> ERROR: Can't GetServerId for $sinfo\n" if (! defined($slaveId));

if ($slaveId < 0) {
    unlink $fname;
    die "\n>>>>>>>>>>>>> ERROR: GetServerId returned $slaveId < 0\n";
}
#SyncSync($mconn, $sconn);

my $masterId = GetServerId($mconn, $master, $masterhost);

die "\n>>>>>>>>>>>>> ERROR: Can't GetServerId for $sinfo\n" if (! defined($masterId));

if ($masterId < 0) {
    unlink $fname;
    die "\n>>>>>>>>>>>>> ERROR: GetServerId returned $masterId < 0\n";
}
#SyncSync($sconn, $mconn);

print "Using snapshot file: $snapshot\n" if ($debug);

my $outf = new IO::File;
open $outf, ">$snapshot";
print "\n>>>>>>>>>>>>> Prepare Snapshot\n\n" if ($verbose);
print "master id: $masterId slave id: $slaveId\n" if ($debug);
#my $res = PrepareSnapshot($mconn, $sconn, $outf, $masterId, $slaveId, $multimaster, $tables);
my $res = PrepareSnapshot($mconn, $sconn, $outf, $masterId, $slaveId, $multimaster);
close $outf;
if ($res < 0) {
    unlink $fname;
    die "\n>>>>>>>>>>>>> ERROR\n";
}
if ($res == 0)
{
    print "\n>>>>>>>>>>>>> DBases are sync-ed\n" if ($verbose);
    unlink $snapshot unless ($debug);
    unlink $fname;
    exit(0);
}

my $inpf = new IO::File;
open $inpf, "<$snapshot";
print "\n>>>>>>>>>>>>> Apply Snapshot\n\n" if ($verbose);
#$res = ApplySnapshot($sconn, $inpf, $multimaster, $tables);
$res = ApplySnapshot($sconn, $inpf, $multimaster);
close $inpf;
if ($res < 0) {
    unlink $fname;
    die "\n>>>>>>>>>>>>> ERROR\n";
}

if ($res > 0)
{
    print "Snapshot applied\n" if ($verbose);
    unlink $snapshot unless ($debug);
    SyncSync($mconn, $sconn);
}

unlink $fname;
exit(0);

###########################################################################

sub SyncSync
{
    ($mconn, $sconn) = @_;

    print "\n>>>>>>>>>>>>> Sync SyncID\n\n" if ($verbose);
    print "Get last SyncID from Slave DB\n" if ($verbose);
    my $syncid = GetSyncID($sconn);
    if ($syncid && $syncid > 0)
    {
	print "Last SyncID applied: $syncid\n" if ($verbose);
	print "Sync SyncID\n" if ($verbose);

	$res = SyncSyncID($mconn, $slaveId, $syncid);

	print "Succeeded\n" if (($res > 0) && ($verbose));
    }
}
