<?php
    include_once '../account/session.php';
    include_once '../../scripts/bdd.php';

    $id_manager=$_SESSION['id-manager'];
    $username_manager=$_SESSION['username-manager'];

    if($_SESSION["type"] != "admin") {
    	die("404 PAGE NOT FOUND !");
    }

    if(isset($_POST) AND !empty($_POST["server"]) AND !empty($_POST["domain"]) AND !empty($_POST["hostname"]) AND !empty($_POST["relay"]) AND !empty($_POST["ips"]) AND !empty($_POST["ip_local"])) {
    	$query = $bdd->prepare("SELECT * FROM server WHERE id = ?");
    	$query->execute(array($_POST["server"]));
    	if($query->rowCount() > 0) {
    		$server = $query->fetch(PDO::FETCH_OBJ);

    		$ip = $server->main_ip;
    		$ip_local = $_POST["ip_local"];
    		$login = $server->login;
    		$password = $server->password;
    		$domain = $_POST["domain"];
    		$hostname = $_POST["hostname"];
    		$relay = $_POST["relay"];
    		$ips = $_POST["ips"];
    		$port = 22;

    		function getChaine($smtp = false,$av,$var)
    		{
    			$chaine = "";
    			foreach(explode(chr(10), $var) as $v) {
    				if(!$smtp) {
    					$chaine .= $av.' '.trim($v)."\r\n";
    				} else {
    					$chaine .= $av.' '.trim($v).":25\r\n";
    				}
    				
    			}
    			return $chaine;
    		}

    		function replaceTags($isfile = true,$file,$tag,$content)
    		{
    			if($isfile == true) {
    				$file = @file_get_contents($file);
    			}
				if($file) {
				    $file = str_replace($tag, $content, $file);
				    return $file;
				}
    		}

    		function show_status($update,$delay = null)
			{
				if(is_null($delay)) {
					$delay = 0;
				}
		        echo $update;
		        ob_flush();
		        flush();
		        sleep($delay);
		    }
    		

    		$connection = ssh2_connect($ip, $port);
			if (ssh2_auth_password($connection, $login, $password)) {

				foreach(file('shell/commands') as $line) {
					ssh2_exec($connection, trim($line));
				}
				show_status("------------- OUTILS -> OK !<br>");
				
				ssh2_exec($connection, "mkdir /var/www/app");
				$name_zip = 'app_'.uniqid();
				exec('zip -r '.$name_zip.' /home/install/slave/');
				ssh2_exec($connection, "wget -P /var/www/app http://".$_SERVER["SERVER_NAME"]."/app/manager/install/".$name_zip.".zip");
				sleep(5);
				ssh2_exec($connection, "touch /var/www/app/extract.sh");
				ssh2_exec($connection, 'echo "unzip -d /var/www/app/ -oq /var/www/app/'.$name_zip.'.zip" >> /var/www/app/extract.sh');
				ssh2_exec($connection, "chmod u+x /var/www/app/extract.sh");
				ssh2_exec($connection, 'cd /var/www/app/;'
                            . './extract.sh');
				ssh2_exec($connection, "mv /var/www/app/home/install/slave/ /var/www/");
				ssh2_exec($connection, "rm -Rf /var/www/app/");
				ssh2_exec($connection, "mv /var/www/slave/ /var/www/app/");

				show_status("------------- APPLICATION DOWNLOAD -> OK !<br>");
				show_status("------------- APPLICATION CONFIG -> OK !<br>");
				show_status("------------- APPLICATION INSTALL -> OK !<br>");

				

				ssh2_scp_send($connection, '/home/install/pmta/pmta.rpm', '/home/pmta.rpm', 0644);
				show_status("------------- SEND PMTA -> OK !<br>");

				foreach(file('shell/pmta') as $line) {
					ssh2_exec($connection, trim($line));
				}
				show_status("------------- PMTA INSTALL -> OK !<br>");

				ssh2_scp_send($connection, '/home/install/pmta/license', '/etc/pmta/license', 0644);
				$file_1 = replaceTags(true,'/home/install/pmta/config',"[RELAY_DOMAIN]",getChaine(false,'relay-domain',$relay));
				$file_2 = replaceTags(false,$file_1,"[SMTP_LISTENER]",getChaine(true,'smtp-listener',$ips));
				$content = "\n<source ".$ip.">\n".
				   "\talways-allow-relaying yes\n\t".
				   "smtp-service yes \n\t".
				   "process-x-envid true\n\t".
				   "process-x-job true\n\t".
				   "process-x-virtual-mta true\n\t".
				   "add-received-header no\n\t".
				   "hide-message-source     true\n\t".
				   "remove-header vectparam\n\t".
				   "log-connections yes\n\t".
				   "log-data no\n\t".
				   "log-commands no\n".
				"</source>\n\t";
				$file_final = replaceTags(false,$file_2,"[SOURCE]",$content);
				$name_file = 'config_virtual_'.uniqid();
				$file = fopen('/var/www/app/manager/install/'.$name_file, 'w');
					fwrite($file, $file_final);
				fclose($file);
				ssh2_scp_send($connection, '/var/www/app/manager/install/'.$name_file, '/etc/pmta/config', 0640);
				unlink('/var/www/app/manager/install/'.$name_file);
				show_status("------------- PMTA CONFIG -> OK !<br>");

				ssh2_exec($connection, "touch /etc/pmta/domainKeys/Dk.".$domain.".pem");
				ssh2_exec($connection, "openssl genrsa -out /etc/pmta/domainKeys/Dk.".$domain.".pem 1024");
				ssh2_exec($connection, "openssl rsa -in /etc/pmta/domainKeys/Dk.".$domain.".pem -out /var/www/html/public_key.txt -pubout -outform PEM");
				show_status("------------- PMTA DKIM -> OK !<br>");

				ssh2_exec($connection, "hostname ".$hostname);
				show_status("------------- HOSTNAME -> OK !<br>");

				foreach(file('shell/iptables') as $line) {
					ssh2_exec($connection, trim($line));
				}


				$httpd = replaceTags(true,'/home/install/httpd/httpd.conf',"[IP]",$ip);
				$file = fopen('/var/www/app/manager/install/httpd.conf', 'w');
					fwrite($file, $httpd);
				fclose($file);
				ssh2_scp_send($connection, '/var/www/app/manager/install/httpd.conf', '/etc/httpd/conf/httpd.conf', 0644);
				exec("rm -Rf /var/www/app/manager/install/httpd.conf");
				ssh2_scp_send($connection, '/home/install/php/php.ini', '/etc/php.ini', 0644);
				ssh2_exec($connection, 'echo "apache ALL=(ALL) NOPASSWD:/usr/sbin/pmta,/etc/init.d/pmta" >> /etc/sudoers');

				exec("rm -Rf /var/www/app/manager/install/".$name_zip.".zip");

				ssh2_exec($connection, "chmod 777 -R /var/www/app/image");
				ssh2_exec($connection, "chmod 777 -R /var/www/app/mailer/campaign/instance");
				ssh2_exec($connection, "chmod 777 -R /var/www/app/mailer/campaign2/instance");
				ssh2_exec($connection, "chmod 777 -R /var/www/app/mailer/server/vmta/config.d");
				ssh2_exec($connection, "chmod 777 -R /var/www/app/mailer/server/access/config.d");
				show_status("------------- APPLICATION PERMISSIONS -> OK !<br>");

				ssh2_exec($connection, "setsebool -P httpd_can_network_connect_db 1");
				
				show_status("------------- Before accessing the server, please restart and save the following modules: <br>
				&nbsp; - httpd <br>
				&nbsp; - pmta <br>
				&nbsp; - iptables <br>");

				show_status("------------- <font style='font-weight:bold;'> ADD DKIM DNS </font> -> <a href='http://".$ip."/html/public_key.txt' target='_blank'>Click here</a> !<br>");
				show_status("------------- <font color='red';>INSTALL FINISH !</font>");
			} else {
			  die('Error login server');
			}
			unset($connection);

    	} else {
    		die("Please refresh page !");
    	}
    } else {
    	die("Please check form !");
    }
    
?>