#!/usr/bin/php -q
<?php
set_error_handler("customError");
//definovanie nazvu suboru s landmarkmi
$subor_landmarks = "vsetky_landmarky.txt";
///////////////////////////////////////

$filename = $subor_landmarks;
$file = file_get_contents($filename);
$landmarks=json_decode($file,true);

$landmark_measure = array();

//prvy landmark v poli 
echo "\nPING to IP => [ms]";
foreach($landmarks as $key1 => $pole1)
{ 
		echo "\nPripojenie na landmark: ".$pole1["hostname"]."\n";
	    $host = $pole1["hostname"];
	    $host_ip = $pole1["ip"];
		$host_id = $pole1["id"];
	
	$testping = control_ping($host_ip);
	
	
	if(empty($testping)){
		$date = Date("d/m/Y H:i:s", Time());
		trigger_error("$date   NEODPOVEDA na ping - Landmark ID: $host_id - IP address: $host_ip - Hostname: $host");
		//zapis nulovej hodnoty pre neuspesnu odpoved z landmarku 
		$json_string = json_encode (null);
		$soubor = fopen("./bestline-$host.txt", "w");
		fwrite($soubor, $json_string);
		fclose($soubor);
		
		
	}else{
	
	//Vytvorenie ssh spojenia na landmarky
	$ssh = @ssh2_connect($host, 22, array('hostkey'=>'ssh-rsa'));
	if(!$ssh) {
		echo "Chyba - Neda sa spojit s ssh serverom.\n";
		$date = Date("d/m/Y H:i:s", Time());
		trigger_error("$date   NEUSPESNE pripojenie s ssh serverom ID: $host_id - IP address: $host_ip - Hostname: $host");	
		//zapis nulovej hodnoty pre neuspesne pripojenie k landmarku 
		$json_string = json_encode (null);
		$soubor = fopen("./bestline-$host.txt", "w");
		fwrite($soubor, $json_string);
		fclose($soubor);
	}else{
		echo "Uspesne pripojeny.\n";
		
	//Prihlasenie na server
	$sshLogin = @ssh2_auth_pubkey_file($ssh, 'cesnet_vutbr2', '/home/peter/keys_rsa/identity.pub', '/home/peter/keys_rsa/identity');
	if(!$sshLogin) {
		echo "Chyba - Neda sa prihlasit na server.\n";
		$date = Date("d/m/Y H:i:s", Time());
				trigger_error("$date   NEUSPESNE prihlasenie na ssh server ID: $host_id - IP address: $host_ip - Hostname: $host");
		
	}else{
		echo "Uspesne prihlaseny.\n";
		
		//druhy merany landmark
		$filename = $subor_landmarks;
		$file = file_get_contents($filename);
		$landmarks1=json_decode($file,true);
		unset($landmarks1[$key1]);
		foreach($landmarks1 as $key2 => $pole2)
		{
			//echo "\n". $pole2["ip"];
		if($pole1["latitude"] != $pole2["latitude"] && $pole1["longitude"] != $pole2["longitude"]) {
		
			//vypocet vzdialenosti k pingovanemu landmarku v zavislosti k aktualnemu landmarku
			$lat1 = $pole1["latitude"];
			$lng1 = $pole1["longitude"];
			$lat2 = $pole2["latitude"];
			$lng2 = $pole2["longitude"];
			$distance_landmark = distance($lat1, $lng1, $lat2, $lng2, $miles = false);
		    
		    $distance_xy = sqrt((pow(($lat1 - $lat2),2))+(pow(($lng1 - $lng2),2)));
		    
		    $IP = $pole2["ip"];
		    echo "$IP ";
			$stream = ssh2_exec($ssh, 'ping -q -i 0.5 -c 10 '."$IP".' | grep rtt | sed -e \'s/.*mdev = \([^\/]*\).*/\1/\'');
			stream_set_blocking($stream, true);
			$ping_result = "";
				while($buffer = fread($stream, 4096)) 
				{
					$ping_result .= $buffer;					
				}
			if (empty($ping_result)) {$ping_measure = "Ziadna odozva\n"; }else{$ping_measure = $ping_result;}
					echo " => $ping_measure";
		    
		    
		    //pokial nie je ping bez odozvy tak zapise IP, vypocitanu vzdialenost a ping k landmarku od aktualneho landmarku
			if (!empty($ping_result))
			{
				$landmark_measure[$host][$key2] = array("ip" => $pole2["ip"],"distance" => $distance_landmark,"ping" => $ping_result,"distance_xy" => $distance_xy);						
			}			
		}else{
			continue;
			}
		//koniec 2. foreach	
		}
		//print_r($landmark_measure[$host]);
		echo "\n";
		
		
		/////////////////////////////////////
		///ZACIATOK - HLADANIE MINIMA///
			$hosts = $landmark_measure[$host];

			//odstrani hodnoty nevyhovujuce podmienke baseline
			$hosts = remove_baseline_value($hosts);
						
			//zoradi ping od najmensieho po najvacsi
			usort($hosts, "cmp_ping");		
			
			foreach ($hosts as $kluc1 => $ping1){
				unset($hosts[$kluc1]);
				
				foreach($hosts as $kluc2 => $ping2){					
					if($ping2["distance"] < $ping1["distance"]) {								
								$Ax = $ping2["distance"];
								$Ay = $ping2["ping"];
								$Az = $ping2["distance_xy"];
							   
								$Bx = $ping1["distance"];
								$By = $ping1["ping"];
								$Bz = $ping1["distance_xy"];	
								echo "\n".$Ax ." ". $Ay ." ". $Bx ." ". $By."\n";
								
								$a1 = "1";//q
								$b1 = $Ax;//x1 distance
								$c1 = $Ay;//y1 ping	
								$d1 = $Az;//distance pocitane z X a Y suradnic pytag.vetou
															
								$a2 = "1";//q
								$b2 = $Bx;//x2 distance
								$c2 = $By;//y2 ping
								$d2 = $Bz;//distance pocitane z X a Y suradnic pytag.vetou
								
								
								$detA = (($a1*$b2) - ($b1*$a2));
								$detA1 = (($c1*$b2) - ($b1*$c2));
								$detA2 = (($a1*$c2) - ($c1*$a2));
								
								$q = null;
								$k = null;
								if ($detA != 0) 
								{
									$q = ($detA1/$detA);
									$k = ($detA2/$detA);
								}					
								
								
						echo "K: ".$k." Q: ".$q."\n";			
					}else{			
								$Ax = $ping1["distance"];
								$Ay = $ping1["ping"];
								$Az = $ping1["distance_xy"];
								
								$Bx = $ping2["distance"];
								$By = $ping2["ping"];
								$Bz = $ping2["distance_xy"];
									
								echo "\n".$Ax ." ". $Ay ." ". $Bx ." ". $By."\n";
								
								$a1 = "1";//q
								$b1 = $Ax;//x1 distance
								$c1 = $Ay;//y1 ping
								$d1 = $Az;//distance pocitane z X a Y suradnic pytag.vetou
								
								$a2 = "1";//q
								$b2 = $Bx;//x2 distance
								$c2 = $By;//y2 ping
								$d2 = $Bz;//distance pocitane z X a Y suradnic pytag.vetou
								

								$detA = (($a1*$b2) - ($b1*$a2));
								$detA1 = (($c1*$b2) - ($b1*$c2));
								$detA2 = (($a1*$c2) - ($c1*$a2));
								
								$q = null;
								$k = null;
								if ($detA != 0) 
								{
									$q = ($detA1/$detA);
									$k = ($detA2/$detA);
								}
								
								
						echo "K: ".$k." Q: ".$q."\n";			
					} 
					//podmienka pre baseline
					if ($q >= 0 && $k >= (1.00069228558 * pow(10, -8))) 				
										break 2;
				}
				
			}
			$K = array("k" => $k, "q" => $q);

			print_r($K);



			//zapis bestline do suboru
			$bestline = $K;
			//kontrola ak je vysledne pole prazdne zapise do suboru bestline s hodnotou null
				if(empty($bestline)){
				$json_string = json_encode (null);
				}else{
				$json_string = json_encode ($bestline);	
				}				
			$soubor = fopen("./bestline-$host.txt", "w");
			fwrite($soubor, $json_string);
			fclose($soubor);
		
		///KONIEC - HLADANIE MINIMA///
		/////////////////////////////////////
		
		
		
		
		@fclose($stream);
	//koniec if(ssh2_auth_pubkey_file)
	}
	   
	//koniec if($ssh = ssh2_connect()) 
	}
 //koniec control_ping
 }
//koniec 1.foreach
}


//funkcia pre prepocet uhlov dvoch bodov na geo vzdialenost
function distance($lat1, $lng1, $lat2, $lng2, $miles = false)
  {
    $pi80 = M_PI / 180;
    $lat1 *= $pi80;
    $lng1 *= $pi80;
    $lat2 *= $pi80;
    $lng2 *= $pi80;
     
    $r = 6372.797; // radius of Earth in km
    $dlat = $lat2 - $lat1;
    $dlng = $lng2 - $lng1;
    $a = sin($dlat / 2) * sin($dlat / 2) + cos($lat1) * cos($lat2) * sin($dlng / 2) * sin($dlng / 2);
    $c = 2 * atan2(sqrt($a), sqrt(1 - $a));
    $km = $r * $c;
     
    return ($miles ? ($km * 0.621371192) : $km);
  }	

/* ODSTRANI HODNOTY POD BASELINE => $hosts obsahuje zoradene hodnoty podla vzdialenosti pole(IP,DISTANCE,PING) */
function remove_baseline_value($hosts){
	foreach ($hosts as $key => $hodnota) {
				
		//distance
		$X = $hodnota["distance"];
		//ping
		$Y = $hodnota["ping"];
		
		if($X != 0)
		{
		$k_base = $Y/$X;
		
			if($k_base < (1.00069228558 * pow(10, -8))){
			//echo "\nNevyhovujuci bod: ". $hodnota[$key] ;
			unset($hosts[$key]);
		}
			}
		
	}	
	return $hosts;
}

//funkcia pre kontrolu ci landmark odpoveda na ping
function control_ping($host_ip) {
		$testping = exec('ping -q -i 0.5 -c 4 '."$host_ip".' | grep rtt | sed -e \'s/.*mdev = \([^\/]*\).*/\1/\'');	
		return $testping;
	}
	
	
function cmp_distance($a, $b)
{
    if ($a["distance"] == $b["distance"]) {
        return 0;
    }
    return ($a["distance"] < $b["distance"]) ? -1 : 1;
}	

function cmp_ping($a, $b)
{
    if ($a["ping"] == $b["ping"]) {
        return 0;
    }
    return ($a["ping"] < $b["ping"]) ? -1 : 1;
}	


//definovanie vlastneho error handleru
function customError($error_num, $error_msg, $error_file, $error_line) {     
   $date = Date("d/m/Y H:i:s", Time());
   $file_name = "./error.log";
 switch( $error_num ){   
   case 1024:
	   $error = "\"". $error_msg ."\"\n";         
	   $soubor = fopen($file_name, "a");
	   fwrite($soubor, $error); 
	   break;   
   case 1:
	   $error = "\n" . $date . " ERROR: \"". $error_msg ."\" riadok ". $error_line. " v subore ".$error_file ."\n" ;         
	   $soubor = fopen($file_name, "a");
	   fwrite($soubor, $error); 
	   break;   
   case 2:
	   $error = "\n" . $date . " WARNING: \"". $error_msg ."\" riadok ". $error_line. " v subore ".$error_file ."\n" ;         
	   $soubor = fopen($file_name, "a");
	   fwrite($soubor, $error); 
	   break;
   case 8:
	   $error = "\n" . $date . " NOTICE: \"". $error_msg ."\" riadok ". $error_line. " v subore ".$error_file ."\n" ;         
	   $soubor = fopen($file_name, "a");
	   fwrite($soubor, $error); 
	   break;
 }
}


?>
