<?php

/**
 * Define a DockerEnvironment
 * @author Administrateur PRINCIPAL
 * @category Plugin
 * @license MIT
 */
class DockerEnvironment extends Entity{

	public $id;
	public $machine; //Machine hôte (Nombre Entier)
	public $client; //Client (Nombre Entier)
	public $domain; //Nom de domaine (Texte Long)
	public $port; //Port docker (Nombre Entier)
	public $mysqlRootPassword; //Pass. Mysql Root (Mot de passe)
	public $mysqlPassword; //Pass. Mysql App (Mot de passe)
	public $git; //Dépot git (Texte Long)
	public $memory = 256; //Mémoire max. (Décimal)
	public $cpu; //Cpu max. (Nombre Entier)
	public $ssl = 0; //SSL (Vrai ou Faux)
	public $state; //Etat (Liste classique)
	public $certificate; //Certificat SSL (string)
	public $comment; //Commentaire (wysiwyg)
	
	protected $TABLE_NAME = 'docker_environment';
	public $entityLabel = 'Environnement';
	public $fields = array(
		'id' => array('type'=>'key', 'label' => 'Identifiant'),
		'machine' => array('type'=>'integer', 'label' => 'Machine hôte','link'=>'plugin/docker/DockerMachine.class.php'),
		'client' => array('type'=>'integer', 'label' => 'Client','link'=>'plugin/client/Client.class.php'),
		'domain' => array('type'=>'textarea', 'label' => 'Nom de domaine'),
		'port' => array('type'=>'integer', 'label' => 'Port docker'),
		'mysqlRootPassword' => array('type'=>'password', 'label' => 'Pass. Mysql Root'),
		'mysqlPassword' => array('type'=>'password', 'label' => 'Pass. Mysql App'),
		'git' => array('type'=>'textarea', 'label' => 'Dépot git'),
		'memory' => array('type'=>'decimal', 'label' => 'Mémoire max.'),
		'cpu' => array('type'=>'integer', 'label' => 'Cpu max.'),
		'ssl' => array('type'=>'boolean', 'label' => 'SSL'),
		'state' => array('type'=>'list', 'label' => 'Etat'),
		'certificate' => array('type'=>'string', 'label' => 'Certificat SSL'),
		'comment' => array('type'=>'wysiwyg', 'label' => 'Commentaire'),
	);

	

	//liste des Etat possibles
	public static function states($key=null){
		$items = array(
			DockerEnvironment::ACTIVE => array('label'=>'Actif') 
		);
		if(!isset($key)) return $items;
		return isset($items[$key]) ? $items[$key] : array('label'=>'Non définis');
	}

	//Colonnes indexées
	public $indexes = array();

	public function acronym(){
		return 'wp_';
	}

	public static function lastPort(){
		$lastPort = DockerEnvironment::staticQuery('SELECT max(port) as port FROM {{table}}')->fetch();
		return $lastPort!= false && is_numeric($lastPort['port']) ? $lastPort['port'] : 8008;
		

	}

	public function execute($ssh){
		require_once(__DIR__.SLASH.'SshClient.class.php');
		$clientDirectory = '/home/clients/'.$this->domain;
		return SshClient::format_output($ssh->execute('cd '.$clientDirectory.' && docker-compose up -d'));
	}

	public function createPma($ssh){
		require_once(__DIR__.SLASH.'SshClient.class.php');
		
		$logs = $ssh->execute('docker run --name myadmin -e UPLOAD_LIMIT=5G -d --network=proxy --link '.$this->domain.'_db:db -p 8011:80 phpmyadmin/phpmyadmin');
		return $logs;
	}
	public function removePma($ssh){
		require_once(__DIR__.SLASH.'SshClient.class.php');
	
		$logs = '<br>Remove container myadmin...<br>';
		$logs .= SshClient::format_output($ssh->execute('docker container stop myadmin && docker container rm myadmin'));
	
		return $logs;
	}

	public function removeContainer($ssh){
		require_once(__DIR__.SLASH.'SshClient.class.php');
		$clientDirectory = '/home/clients/'.$this->domain;
		if($clientDirectory == '/home/clients/') throw new Exception("Cant delete root !!!");
		if(strlen($clientDirectory) <= strlen('/home/clients/') ) throw new Exception("Cant delete root or root parent!!!");
		$logs = 'Remove vhost...<br>';
		$logs .= $ssh->execute('rm /etc/nginx/sites-available/'.$this->domain.'.conf');
		$logs .= $ssh->execute('rm /etc/nginx/sites-enabled/'.$this->domain.'.conf');
		$logs .= '<br>Reload nginx...<br>';
		$logs .= $ssh->execute('service nginx reload');

		$logs .= '<br>Remove containers '.$clientDirectory.'...<br>';
		$logs .= SshClient::format_output($ssh->execute('docker container stop '.$this->domain.'_wp && docker container rm '.$this->domain.'_wp'));
		$logs .= SshClient::format_output($ssh->execute('docker container stop '.$this->domain.'_db && docker container rm '.$this->domain.'_db'));

		$logs .= '<br>Remove client directory '.$clientDirectory.'...<br>';
		$logs .= $ssh->execute('rm '.$clientDirectory.' -r');
		return $logs;
	}

	public function createContainer($ssh){
		require_once(__DIR__.SLASH.'SshClient.class.php');
		$clientDirectory = '/home/clients/'.$this->domain;
		$logs = $ssh->execute('cp /home/client-template '.$clientDirectory.' -r');

		$localEnv = 'DB_CONTAINER='.$this->domain.'_db';
		$localEnv .="\n".'DB_NAME='.$this->domain;
		$localEnv .="\n".'DB_USER='.$this->domain;
		$localEnv .="\n".'DB_PASSWORD='.decrypt($this->mysqlPassword);
		$localEnv .="\n".'DB_ROOT_PASSWORD='.decrypt($this->mysqlRootPassword);
		$localEnv .="\n".'WP_CONTAINER='.$this->domain.'_wp';
		$localEnv .="\n".'WP_TABLE_PREFIX='.$this->acronym();
		$localEnv .="\n".'WP_PORT='.$this->port;
		$localEnv .="\n".'PMA_CONTAINER='.$this->domain.'_pma';
		$localEnv .="\n".'PMA_PORT='.($this->port+1);
		$localEnv .="\n".'DB_RAM_LIMIT=800M';
		$localEnv .="\n".'DB_RAM_RESERVATION=600M';
		$localEnv .="\n".'WP_RAM_LIMIT='.$this->memory.'M';
		$localEnv .="\n".'WP_RAM_RESERVATION=100M';
		$localEnv .="\n".'PMA_RAM_LIMIT=200M';
		$localEnv .="\n".'PMA_RAM_RESERVATION=100M';
		$localEnv .="\n".'DOMAIN='.$this->domain;
		$localEnv .="\n".'URL=https://'.$this->domain;
		$localEnv .="\n".'POSTFIX_CONTAINER='.$this->domain.'_postfix';
		$localEnv .="\n".'POSTFIX_PORT='.($this->port+2);

		

		$logs .= $ssh->send_stream($localEnv,$clientDirectory.'/.env');

		$vhost = 'server {
	listen 80;
	server_name '.$this->domain.';
	error_log '.$clientDirectory.'/log/proxy_error.log;
	location / {
		proxy_pass http://127.0.0.1:'.$this->port.';
		proxy_set_header Host $host;
		proxy_set_header Upgrade $http_upgrade;
	    proxy_set_header Connection "upgrade";
		proxy_set_header X-Real-IP $remote_addr;
	    proxy_set_header X-Forward-For $proxy_add_x_forwarded_for;
	    proxy_set_header X-Forward-Proto http;
	    proxy_set_header X-Nginx-Proxy true;
	}
}

server {
	listen 80;
	server_name www.'.$this->domain.';
	error_log '.$clientDirectory.'/log/proxy_error.log;
	location / {
		proxy_pass http://127.0.0.1:'.$this->port.';
		proxy_set_header Host $host;
		proxy_set_header Upgrade $http_upgrade;
	    proxy_set_header Connection "upgrade";
		proxy_set_header X-Real-IP $remote_addr;
	    proxy_set_header X-Forward-For $proxy_add_x_forwarded_for;
	    proxy_set_header X-Forward-Proto http;
	    proxy_set_header X-Nginx-Proxy true;
	}
}';
		$logs .= $ssh->send_stream($vhost,'/etc/nginx/sites-available/'.$this->domain.'.conf');
		$logs .= $ssh->execute('ln -s /etc/nginx/sites-available/'.$this->domain.'.conf /etc/nginx/sites-enabled/'.$this->domain.'.conf');
		$logs .= $ssh->execute('service nginx reload');
		return SshClient::format_output($logs);
	}

}
?>