<?php

/**
 * @author  Martin Duclos <martinrduclos@gmail.com>
 * @version 0.9.1
 */

function usage()
{
echo<<<EOF
usage:
	{$GLOBALS['argv'][0]} -c critical_delay -w warning_delay [-h mysqlserver] [-u user] [-p password]
		-h	mysql server [localhost]
		-u 	mysql account that has access to show processlist and show slave status [root]
		-p	password to the mysql account []
		-c	raise critical delay if replication delay is greater then specificed value
		-w 	raise warning delay if replication delay is greater then specificed value
		-h	help, this screen

EOF;
exit();
}

	$opt = getopt('h:u:p:c:w:');
	if ( !isset($opt['h']) ) $opt['h'] = 'localhost';
	if ( !isset($opt['u']) ) $opt['u'] = 'root';
	if ( !isset($opt['p']) ) $opt['p'] = '';
	
	if ( !isset($opt['w']) ) {
		echo "warning delay (-w) is required\n";
		usage();
	}
	
	if ( !isset($opt['c']) ) {
		echo "critical delay (-c) is required\n";
		usage();
	}
	
	$opt['c'] = (int)$opt['c'];
	$opt['w'] = (int)$opt['w'];
	
	if ( $opt['w'] > $opt['c'] ) {
		echo "warning delay (-w ".$opt['w'].") has to be less then critical delay (-c ".$opt['c'].")\n";
		usage();
	}
	
	$errstr = 'mysql server @ ('.$opt['h'].') as user ('.$opt['u'].')';
	
	if ( !@mysql_connect($opt['h'], $opt['u'], $opt['p']) ) {
		echo 'CRITICAL: unable to connect to '.$errstr.': '.mysql_error()."\n";
		exit(2);
	}

	if ( !($r = mysql_query($sql='show slave status')) ) {
		echo 'CRITICAL: unable to retrieve slave status via ('.$sql.'): '.mysql_error()."\n";
		exit(2);
	}

	$errno = 0;
	$slave_status = Array();
	$host_up = 0;
	$host_down = 0;
	while( $row = mysql_fetch_assoc($r) ){
		//print_r($row);
		$ch = $row['Master_Host'];
		if ( $row['Slave_IO_Running'][0] != 'Y' || $row['Slave_SQL_Running'][0] != 'Y' ) {
			array_push( $slave_status, 'CRITICAL: Master '.$ch.', replication is down Slave_IO_Running('.$row['Slave_IO_Running'].')/Slave_SQL_Running('.$row['Slave_SQL_Running'].");" );
			$errno = 2;
			$host_down++;
			continue;
		}
		else {
			$val = $row['Seconds_Behind_Master'];
			if ( $opt['c'] < $val ) {
		        	array_push( $slave_status, 'CRITICAL: Master '.$ch.", replication delay is $val; " );
               			$errno = 2;
				$host_up++;
				continue;
        		}
       			else if ( $opt['w'] < $val ) {
               			array_push( $slave_status, 'WARNING: Master '.$ch.", replication delay is $val; " );
               			if( $errno == 0 ){
					$errno = 1;
				}
				$host_up++;
				continue;
       			}
			else {
                		array_push( $slave_status,  'OK: Master '.$ch.", replication delay is $val; " );
				$host_up++;
				continue;
			}
       		}
	}
	$hosts_count = $host_up + $host_down;
	if( $hosts_count > 1 ) print "STATUS: $host_up of " . $hosts_count . " slaves are running. ";
	foreach(  $slave_status as $str ) print $str;
	print "\n";
	exit($errno);

?>
