<?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)) {
		extract($_POST);
		if(!empty($server) AND !empty($main_ip) AND !empty($ips)) {
			$file = fopen("ips.txt", "w");
			foreach(explode(chr(10), $ips) as $ip)
			{
				fwrite($file, $ip."\n");
			}
			fclose($file);

			$query = $bdd->prepare("SELECT * FROM server WHERE id = ?");
	    	$query->execute(array($server));
	    	$server = $query->fetch(PDO::FETCH_OBJ);

	    	$login = $server->login;
	    	$password = $server->password;
	    	$port = 22;

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

				ssh2_scp_send($connection, "/var/www/app/manager/install/ips.txt", "/home/ips.txt");
				ssh2_scp_send($connection, '/var/www/app/manager/install/networkconf.sh', "/home/networkconf.sh");
				ssh2_exec($connection, "yum -y install dos2unix");
				ssh2_exec($connection, "dos2unix /home/ips.txt");
				ssh2_exec($connection, "dos2unix /home/networkconf.sh");
				ssh2_exec($connection, "chmod u+x /home/networkconf.sh");
				ssh2_exec($connection, "rm -f /etc/sysconfig/network-scripts/ifcfg-eth0:*");
				ssh2_exec($connection, 'cd /home/;'
					.'./networkconf.sh '.$main_ip);
			}
			unlink("ips.txt");
			unset($connection);
			echo "----------- FINISH !";
		}
	}