#!/usr/bin/php -q
<?php

define('OK', 0);
define('WARNING', 1);
define('CRITICAL', 2);
define('UNKNOWN', 3);

$mysql_host 	= "127.0.0.1";
$mysql_username = "nagios";
$mysql_password = "";

$sql = "show slave status";
if(false === $link = mysql_connect($mysql_host,$mysql_username,$mysql_password)) {
	echo "Could not connect to database.\n";
	echo mysql_error();
	die(CRITICAL);	
}

if(false === $result = mysql_query($sql)) {
	echo "Unable to query database\n";
	echo mysql_error();
	die(CRITICAL);	
}

if(!mysql_num_rows($result)) {
	echo "SHOW SLAVE STATUS returned no rows.\n";
	echo mysql_error();
	die(CRITICAL);	
}

$data = mysql_fetch_assoc($result);

$seconds = $data['Seconds_Behind_Master'];

if($data['Slave_SQL_Running'] != 'Yes' || $data['Slave_IO_Running'] != 'Yes') {
	echo "Slave replication stopped, IO or SQL Error. Here is the output of SHOW SLAVE STATUS\n\n";
	print_r($data);
	die(CRITICAL);									
}

if($seconds > 300) {
	echo "Slave is more than five minutes behind master.\n";
	die(CRITICAL);						
}
if($seconds > 60) {
	echo "Slave is more than one minute behind master. Damn lag!\n";
	die(WARNING);						
} else {
	echo 'Slave up to date|' . $seconds;
	die(OK);
}





