<?php
/*
Pour utiliser cette classe, penser a ajouter le paquet :
apt-get install php7.2-ssh
service apache2 reload
*/
class SshClient{
	
	public $connection;
	public function connect($ip,$port = 22,$publicKeyPath,$privateKeyPath,$privateKeyPassword = ''){
		$this->connection = ssh2_connect($ip, $port, array('hostkey'=>'ssh-rsa'));

		if (!ssh2_auth_pubkey_file($this->connection, 'root',
                         $publicKeyPath ,
                         $privateKeyPath, $privateKeyPassword)) throw new Exception("Authentification par clé loupée");

	}
	
	public function send_file($localPath,$remotePath,$permissions = 0755){
		return ssh2_scp_send($this->connection, $localPath, $remotePath,$permissions);
	}

	public function send_stream($stream,$remotePath,$permissions = 0755){
		$tempPath = File::temp().SLASH.sha1(rand(0,1000));
		file_put_contents($tempPath, $stream);
		$return = $this->send_file($tempPath,$remotePath);
		unlink($tempPath);
		return $return;
	}

	public function execute($command){
	  $stream = ssh2_exec($this->connection, $command);
	  $errorStream = ssh2_fetch_stream($stream, SSH2_STREAM_STDERR);

	  stream_set_blocking($errorStream, true);
	  stream_set_blocking($stream, true);

	  $error = stream_get_contents($errorStream);
	  $response = stream_get_contents($stream);

	  if(!empty($error)){
	  	$response = $error;
	  }
	  fclose($errorStream);
	  fclose($stream);
	  return $response;
	}

	public static function format_output($output){
		$output = nl2br($output);
		//$output = str_replace('[1A[2K', 'blue ?', $output);
		$output = str_replace('[31m', '<span class="text-danger">', $output);
		$output = str_replace('[32m', '<span class="text-success">', $output);
		$output = str_replace('[0m', '</span>', $output);

		$output = str_replace('[1A[2K', '', $output);
		$output = str_replace('[1B', '', $output);

		return $output;
	}

	public function disconnect(){
		 ssh2_disconnect ($this->connection );
	}


}

?>