#!/usr/bin/perl
use strict;
use Getopt::Long;
use DBI;

our($help);
our($remote_host);
our($remote_user);
our($remote_pass);
our($local_host);
our($local_user);
our($local_pass);
our($configfile) = "/usr/local/opmon/etc/db.php";

sub parse_args
{
	Getopt::Long::Configure('bundling');
	GetOptions(
		"h"   	=> \$help,
		"H=s"   => \$remote_host,
		"U=s"   => \$remote_user,
		"P=s"   => \$remote_pass,
	);

	&usage() if ($help || ! $remote_host 
			|| ! $remote_pass || ! $remote_user);

}

sub usage
{
	print "Usage: $0 -H <remote host> -U <remote user> -P <remote pass>\n";
	exit 0;
}

sub get_local_connection_data
{
	open(F,"<$configfile") ||
		die ("CRITICAL - Impossivel encontrar ou abrir $configfile");

	foreach(<F>) {
		if (m/^.*\$DBUSER=\"(.*)\".*;/) {
			$local_user = $1;
		}
		if (m/^.*\$DBPASS=\"(.*)\".*;/) {
			$local_pass = $1;
		}
		if (m/^.*\$DBHOST=\"(.*)\".*;/) {
			$local_host = $1;
		}
	}
	close(F);
}

sub main
{
	my($local_dsn);
	# my($remote_dsn);
	my($dbh);
	my($sth);
	my(@return);

	# &parse_args();
	&get_local_connection_data();

	$local_dsn = "dbi:mysql:opmon4;$local_host";
	# $remote_dsn = "dbi:mysql:opmon;$remote_host";

	# connect to remote database
	# $dbh = DBI->connect($remote_dsn,$remote_user,$remote_pass) ||
	#	die ("Impossivel conectar a $remote_dsn");

	# $sth = $dbh->prepare("show slave status");
	# $sth->execute();

	# @return = $sth->fetchrow();
	# if ($#return == -1) {
	#	print "CRITICAL - Query show slave status retornou vazia em $remote_dsn\n";
	#	exit 2;
	# }

	# if ($return[10] ne "Yes" || $return[11] ne "Yes") {
	#	print "CRITICAL - Problema de sincronismo mysql, verificar urgente\n";
	#	exit 2;
	# }

	# connect to local database
	$dbh = DBI->connect($local_dsn,$local_user,$local_pass) ||
		die ("Impossivel conectar a $local_dsn");

	$sth = $dbh->prepare("show slave status");
	$sth->execute();

	@return = $sth->fetchrow();
	if ($#return == -1) {
		print "CRITICAL - Query show slave status retornou vazia em $local_dsn\n";
		exit 2;
	}

	if ($return[10] ne "Yes" || $return[11] ne "Yes") {
		print "CRITICAL - Problema de sincronismo mysql, verificar urgente\n";
		exit 2;
	}

	print "OK - Bases sincronizadas\n";
	exit 0;

}

&main();
