#!/usr/bin/env perl

# Use mandatory external modules
use strict;
use Cwd;
use File::Basename;
use Data::Dumper;
use POSIX;
use Config;
use Time::HiRes;
use DBI;

# Determine installation dir name
our $SELF_DIR = dirname(dirname(Cwd::abs_path(__FILE__)));

# Include parts of the system
require $SELF_DIR . '/lib/config.pm';

# Read config file and status
our $config = ReadConfig("mmm_agent.conf");

print SyncWithMaster();

exit(0);

#-----------------------------------------------------------------
sub SyncWithMaster($) {
    my $host = shift;

    my $this = $config->{this};
    
    # get self connection info
    my $host = $config->{host}->{$this}->{ip};
    my $port = $config->{host}->{$this}->{port};
    my $user = $config->{host}->{$this}->{user};
    my $pass = $config->{host}->{$this}->{password};
    my $peer = $config->{host}->{$this}->{peer};

    # get peer connection info
    my $peer_host = $config->{host}->{$peer}->{ip};
    my $peer_port = $config->{host}->{$peer}->{port};
    my $peer_user = $config->{host}->{$peer}->{user};
    my $peer_pass = $config->{host}->{$peer}->{password};
    
    
    my $this_dbh = MysqlConnect($host, $port, $user, $pass);
    return "ERROR: Can't connect to MySQL (host = $host:$port, user = $user)!"  if (!$this_dbh);
    
    my $peer_dbh = MysqlConnect($peer_host, $peer_port, $peer_user, $peer_pass);

    my $wait_log;
    my $wait_pos;
    
    # If can get info from master, do it
    if ($peer_dbh) {
        #print "Will sync with master log...\n";
        my $row = MysqlQuery($peer_dbh, "SHOW MASTER STATUS");
        $wait_log = $row->{File};
        $wait_pos = $row->{Position};
    } else {
        #print "Will sync with relay log...\n";
        my $row = MysqlQuery($this_dbh, "SHOW SLAVE STATUS");
        $wait_log = $row->{Master_Log_File};
        $wait_pos = $row->{Read_Master_Log_Pos};
    }
    
    my $res = ExecuteQuery($this_dbh, "SELECT MASTER_POS_WAIT('$wait_log', $wait_pos)");
    return "ERROR: SQL Query Error: " . $this_dbh->errstr unless($res);
    
    return "OK";
}

#-----------------------------------------------------------------
sub MysqlConnect($$$$) {
    my ($host, $port, $user, $pass) = @_;
    
    my $dsn = "DBI:mysql:host=$host;port=$port";
    return DBI->connect($dsn, $user, $pass, { PrintError => 0 });
}

#-----------------------------------------------------------------
sub MysqlQuery($$) {
    my ($dbh, $query) = @_;

    my $sth = $dbh->prepare($query);
    my $res = $sth->execute;
    return $res unless($res);

    my $row = $sth->fetchrow_hashref;
    $sth->finish;

    return $row;
}

#-----------------------------------------------------------------
sub ExecuteQuery($$) {
    my ($dbh, $query) = @_;

    my $sth = $dbh->prepare($query);
    return $sth->execute;
}
