#!/usr/bin/php
<?php
	define('DEBUG',false);
	define('PLUGINS_PATH','/usr/local/esia/plugins/');
	define('NRPE_PLUGIN',PLUGINS_PATH.'check_nrpe.old');
	define('NRPE_COMMANDS_FILE',PLUGINS_PATH.'nrpe.conf');
	define('ECATP_PLUGIN',PLUGINS_PATH.'check_gesa.php');
	define('ECATP_GESA_LIST','/tmp/ecatp/gesa.list');
	define('ECATP_TIMEOUT',50);
	define('ECATP_RETRY',1);
	define('ECATP_RETRY_TIMEOUT',10);

	$STR_STATUS=array("OK","WARNING","CRITICAL","UNKNOWN");
	$INT_STATUS=array_flip($STR_STATUS);

	function trace($message){
		if( DEBUG != NULL && DEBUG ){
			$time = microtime(true);
			echo "[$time] $message";
			file_put_contents("/tmp/ecatp/check_nrpe","[$time] $message",FILE_APPEND);
		}	
	}

	function getArguments($args){
		do{
			$arg = array_shift($args);
		}while($arg != null && $arg != '-a');
		if( $arg == null ) return array();

		if(count($args) == 1 ) {
			$args = trim($args[0],'"'."'");
			$args = explode(" ",$args);
		}
		return $args;
	}
	
	trace("Arguments ".implode(" ",$argv)."\n");

	//ECATP ou NRPE ?
	$options = getopt("H:S:t:c:a:p:");

	if(empty($options['H']) && empty($options['S'])){
		echo "You forget to specify gesa with SN (-S <SN>) or host (-H <HOST>) parameter\n";
		exit($INT_STATUS['UNKNOWN']);
	}

	if(empty($options["c"])){
		echo "You forget to specify command (-c <command>)\n";
		exit($INT_STATUS['UNKNOWN']);
	}

	$addr_opt = null;
	if(isset($options['H'])){
		$addr_opt = trim($options['H']);
		if(filter_var($addr_opt, FILTER_VALIDATE_IP) === false ){
			trace("gethostbyname");
                        $addr_opt = gethostbyname ( $addr_opt );
                }
	}

	$sn_opt=null;
	if( isset($options['S']) ){
		if(is_array($options['S'])) $options['S'] = array_shift($options['S']);
		$sn_opt=trim($options['S']);
	}

	trace("search SN in GESA LIST\n");
	$content_file = @file_get_contents(ECATP_GESA_LIST);
        if( $content_file !== FALSE ){
                $gesa_list = explode("\n",$content_file);
                foreach($gesa_list as $gesa_row){
                        if( empty(trim($gesa_row)) ) continue; //Empty row
                        $gesa_cells = explode(',',$gesa_row);
                        $ip_addr        = trim($gesa_cells[0]);
                        $hostname       = trim($gesa_cells[1]);
                        $gesa_sn        = trim($gesa_cells[2]);

                        if( $gesa_sn == $sn_opt ) {
                                trace("SN $gesa_sn found\n");
                                $sn_found = $gesa_sn;
                                break;
                        }
                }
                if(!isset($sn_found)&& $addr_opt != null){
                    foreach($gesa_list as $gesa_row){
                            if( empty(trim($gesa_row)) ) continue; //Empty row
                            $gesa_cells = explode(',',$gesa_row);
                            $ip_addr        = trim($gesa_cells[0]);
                            $hostname       = trim($gesa_cells[1]);
                            $gesa_sn        = trim($gesa_cells[2]);

                            if( $ip_addr == $addr_opt ) {
                                    trace("SN $gesa_sn found\n");
                                    $sn_found[] = $gesa_sn;
                            }
                    }
		$nb_sn = count( $sn_found );
		if( $nb_sn > 1 ) {
		        echo "SN $gesa_sn not found (Unity connected ?) and $nb_sn unitys with same ip address ($addr_opt)\n";
			if ( preg_match('/check_gesa/',implode(" ",$argv) ) ) {
				if( preg_match('/-u/',implode(" ",$argv))){
					exit($INT_STATUS['UNKNOWN']);
				}
				else{
					exit($INT_STATUS['CRITICAL']);
				}
			}
			else{
				exit($INT_STATUS['UNKNOWN']);
			}
		}
		else if( $nb_sn == 1){
			$sn_found = array_shift($sn_found);
		}
		else{
			unset($sn_found);
		}
		}
        }
	else{
		trace("File ".ECATP_GESA_LIST." not found.\n");
        }
	if( isset($sn_found) ) { //Mode ECATP 
		trace("ECATP mode\n");	
		$timeout = ECATP_TIMEOUT;
		$command = null;

		if( isset($options["t"] ) ) $timeout = $options["t"];
		if( isset($options["c"] ) ) $command = $options["c"];

		trace("Search command $command\n");
		$content_file = @file_get_contents(NRPE_COMMANDS_FILE);
		if( $content_file !== FALSE ) {
			if( !preg_match("/^\s*command\[$command\]=(.*)$/m",$content_file,$matches) || count($matches) < 2 ){
				echo "Command '$command' not found\n";
				exit($INT_STATUS['UNKNOWN']);
			}
			trace("Command found\n");
			$exp = explode(" ",$matches[1],2);
				
			$file_name = basename($exp[0]);				

			$nrpe_args='';
			if(isset( $exp[1]))	$nrpe_args = $exp[1];

			$plugin_args = $nrpe_args;

			foreach(getArguments($argv) as $key => $value){
				$id = $key+1;
				$plugin_args = preg_replace('/\$ARG'.$id.'\$/',$value,$plugin_args);
			}

			$ecatp_args = "-t $timeout -G $sn_found -C $file_name -A '$plugin_args'";

			$exec_cmd = ECATP_PLUGIN." $ecatp_args";
			trace("Exec $exec_cmd\n");

			$i=ECATP_RETRY;
			do{
                if( $i != ECATP_RETRY ){
                    sleep(ECATP_RETRY_TIMEOUT);
                }
				$output = array();
				$f_row=exec($exec_cmd,$output,$ret);
				$i--;

                $end=true;
                if($i < 0 ) $end = true;
                else if( $ret == 3 ){
                    if(preg_match('/WEBSOCKET/',$f_row) || 
                        preg_match('/NRPE/',$f_row) ||
                        preg_match('/ENDPOINT/',$f_row) ||
                        preg_match('/Error execute: Bad return code/',$f_row) || 
                        preg_match('/EsiaDaemon could not connect to host/',$f_row)){
                        $end = false;
                    }
                }
                else if($ret < 0 || $ret > 3){
                    $end = false;
                }
			}while(!$end);
			trace("Print result and return state $ret\n");
			echo implode("\n",$output)."\n";
            exit($ret);
		}
		else trace("Unable to read file ".NRPE_COMMANDS_FILE." : ".error_get_last()["message"]."\n");
		//On tente alors un mode NRPE. Ci-dessous
	}

	 //NRPE mode
	trace("NRPE mode\n");
	//Arguments pour nrpe
	$old_arguments = $argv;
	array_shift($old_arguments);
	$arguments=array();
	//Afin d'efface l'agument -S et celui qui suit
	for($i=0;$i<count($old_arguments);$i++){
		if( $old_arguments[$i] != '-S' ){
			$arguments[]='"'.$old_arguments[$i].'"';
		}
		else $i++;
	}
	$arguments = implode(' ',$arguments);
	trace("EXEC NRPE WITH $arguments");

	if ( !preg_match('/-H/',$arguments) && preg_match('/check_gesa/',$arguments ) ) {
			echo "Unity not connected\n";
			if( preg_match('/-u/',$arguments)){
			exit($INT_STATUS['UNKNOWN']);
		}
		else{
			exit($INT_STATUS['CRITICAL']);
		}
	}

	exec( NRPE_PLUGIN." $arguments",$output,$ret);	 
	trace("Print result and return state $ret\n");
	echo implode("\n",$output)."\n";
	exit($ret);
?>
