<?php
/*
* Copyright (c) 2009-2010 ATMAIL. All rights reserved
* See http://atmail.com/license.php for license agreement
*/

ini_set('memory_limit', "64M");
error_reporting(E_ALL);

$LIBDIR = 'Atmail/';
if(!is_file('Atmail/Utility.php'))
{
	if(is_file('library/Atmail/Utility.php'))
	{
		$LIBDIR = 'library/Atmail/';
	}
	else if( is_file('/usr/local/atmail/webmail/library/Atmail/Utility.php') )
	{
		$LIBDIR = '/usr/local/atmail/webmail/library/Atmail/';
	}
}

try
{
	require_once($LIBDIR . 'Utility.php');
	require_once($LIBDIR . 'Deps/DepList.php');

}
catch(Exception $e)
{
	die('Unable to include utility');
}

function displayWelcome($mode)
{
	if($mode == true)
	{
		fwrite(STDOUT, "\n\033[1;32mUpdate Dependencies \033[0;39m\n--------------------\n");
		fwrite(STDOUT, "
Before updating Atmail, the utility will check your system has the correct
system dependencies and packages installed to compile, update and configure
the software. If any packages are missing these can be automatically
installed (internet connection required).\n\n");
	}
	else
	{
		fwrite(STDOUT, "\n\033[1;32mInstall Dependencies \033[0;39m\n--------------------\n");
		fwrite(STDOUT, "
Before installing Atmail, the utility will check your system has the correct
system dependencies and packages installed to compile, setup and configure
the software. If any packages are missing these can be automatically
installed (internet connection required).\n\n");
	}

	fwrite(STDOUT, "Required Dependencies:\n\n");
}

function check_deps($input_args, $updateMode = false)
{
	global $mysqlrestart;
	global $redhat_deps;
	global $readynas_deps;
	global $debian_deps;
	global $debian2_deps;
	global $ubuntu_deps;
	global $ubuntu_deps_12xx;
	global $suse_deps;
	/*
	 * Automated installation configuration vars
	 */

	$args = array();
	$argsError = 0;

	// Build a list of arguments
	foreach($input_args as $arg)
	{
		$arr = explode("=", $arg);
		$arr[0] = str_replace('--', '', $arr[0]);
	
		if(empty($arr[1]))
		{

			$arr[1] = "";		

		}
	
		$args[$arr[0]] = $arr[1];
	
	}
    if (isset($args['skipdeps']))
    {
        return true;
    }

// Check suse requirements
// If we are running a system with zypper, install the requirements
	if(file_exists('/etc/SuSE-release') || file_exists('/etc/SuSE-version'))
	{

		$suse = 1;
	
		displayWelcome($updateMode);

		$packages = `rpm -qa`;
		$deplist = "";
		$depcheck = 0;

		foreach($suse_deps as $dep)
		{

			$depquote = preg_quote($dep);

			/*if(!preg_match("/^$depquote/", $packages))*/
			{

				if(strstr($dep, "ii  ")!=null)
				{

					$dep = trim($dep, "ii  ");

				}
				if(strstr($dep, "mysql-")!=null)
				{

					$dep = "mysql";

				}
			
				if (preg_match('/^php5-/', $dep))
				{

					if (extension_loaded(str_replace('php5-', '', $dep)))
					{

						continue;

					}	

				}		
			
				$deps[$dep] = $dep;
				fwrite(STDOUT, " * Required $dep\n");
				$deplist .= "$dep ";
				$depcheck++;
				if($dep == 'php5-mysql')
				{
					
					system('touch .mysqlrestart');
					$mysqlrestart = 1;
					
				}   
				
			}   
			
		}

		if($depcheck > 0)
		{

			if (!isset($args['install']))
			{
				$a = strtolower(prompt("Install dependencies automatically? [Y/n]", "Y"));
			}
			else
			{
				$a = 'y';
			}
		
			if ($a == 'y' || $a == 'yes')
			{
	
				fwrite(STDOUT, "\n\033[1;32mInstalling Packages \033[0;39m\n-------------------\n");
	
				fwrite(STDOUT, "\nInstalling packages via the system 'zypper' installer, please standby\nthis process make take several minutes depending the speed of your network\n\n");
	
				foreach($deps as $dep)
				{
					if($dep == 'libldap-2_4-2')
					{
						// if suse 64, patch
						if (file_exists('/usr/lib64/libldap-2.4.so.2.2.0'))
						{
							system('ln -s /usr/lib64/libldap-2.4.so.2.2.0 /usr/lib64/libldap.so');
							system('export LDFLAGS=-L/usr/lib64');
						}		
					}
					$deplist .= $dep . " ";
				}
			
				system("zypper -n install $deplist");
	
				fwrite(STDOUT, "\n");
			
				// TODO: check suse package success
				{
					fwrite(STDOUT, "\nDependencies successfully installed, proceeding with Atmail configuration.\n");
	
					if (!isset($args['install']))
						prompt('[Press Enter to Continue]');	
				}
				$restart_b = true;
			}
		}
		else
		{
			fwrite(STDOUT, "* All Dependencies are correctly installed.\n");
		}

		// End suse requirements

		if (!file_exists("/etc/apache2/sysconfig.d/include.conf")) 
		{ 
			system("touch /etc/apache2/sysconfig.d/include.conf");
		}
	
		system('/etc/init.d/mysql restart');
	}

	// Check Ubuntu requirements/version 
	// If we are running a system with apt-get, install the requirements

	if((file_exists('/etc/debian_version') || file_exists('/etc/debian_release')) && file_exists('/etc/lsb-release'))
	{

		// Check for lsb-release version
		preg_match('/DISTRIB_RELEASE=(.*)/', file_get_contents("/etc/lsb-release"), $m);

		// Ubuntu 10.4 
		if(version_compare($m[1], '10', '>=')) 
		{
			if(version_compare($m[1], '12', '>=')) {
				$debian_deps = $ubuntu_deps_12xx;
			}
	
			$debian = 1;
	
			displayWelcome($updateMode);

			$packages = `dpkg -l | grep ii`;
			$deplist = "";
			$depcheck = 0;
	    
			foreach($debian_deps as $dep)
			{		

				$depquote = preg_quote($dep);
	
				if(!preg_match("/$depquote/", $packages))
				{
					if(strstr($dep, "ii  ")!=null)
					{
						$dep = trim($dep, "ii  ");
					}
			
					if(strstr($dep, "mysql") != null)
					{
						system('touch .mysqlrestart');
						$mysqlrestart = 1;
					}
	
					
					if (preg_match('/^php5-/', $dep))
					{
						if (extension_loaded(str_replace('php5-', '', $dep)))
						{
							continue;
						}	
					}		
			
					$deps[$dep] = $dep;
					fwrite(STDOUT, " * Missing $dep\n");
					$deplist .= "$dep ";
					$depcheck++;
					if($dep == 'php5-mysql')
					{
						system('touch .mysqlrestart');
						$mysqlrestart = 1;
					}
				}
			}
	
			if($depcheck > 0)
			{
				if (!isset($args['install']))
				{
					$a = strtolower(prompt("Install missing dependencies automatically? [Y/n]", "Y"));
				}
				else
				{
					$a = 'y';
				}
			
				if ($a == 'y' || $a == 'yes')
				{
					fwrite(STDOUT, "\n\033[1;32mInstalling Packages \033[0;39m\n-------------------\n");
					fwrite(STDOUT, "\nInstalling missing packages via the system 'apt-get' installer, please standby\nthis process make take several minutes depending the speed of your network\n\n");
	
					foreach($deps as $dep)
					{
						$deplist .= $dep . " ";
					}
			
					system("apt-get -y install $deplist");
	
					fwrite(STDOUT, "\n");
			
					// Check packages again
					$packages = `dpkg -l`;
					$faildep = "";
			
					foreach($deps as $dep)
					{
						$depquote = preg_quote($dep);
						if(preg_match("/$depquote/", $packages))
						{
							fwrite(STDOUT, " * Installed successfully: $dep\n");	
						}
						else
						{
							fwrite(STDOUT, " * Failed install: $dep\n");
							$faildep++;
						}
					}
	
					if($faildep)
					{
						fwrite(STDOUT, "\n\nCould not successfully install the missing dependencies, please check your connection to the\nnetwork is active and the system 'apt-get' command is installed correctly\n\n");
	
						if (!isset($args['install']))
						{
							prompt('[Press Enter to Continue]');
						}	
					}
					else
					{
						fwrite(STDOUT, "\nMissing dependencies successfully installed, proceeding with Atmail configuration.\n");
	
						if (!isset($args['install']))
						{
							prompt('[Press Enter to Continue]');
						}	
					}
					$restart_b = true;
				}
			}
			else
			{
				fwrite(STDOUT, "* All Dependencies are correctly installed.\n");
			}
			// End Ubuntu 10.4 requirements
		}
		else
		{
		// Ubuntu 9.10 or older	
			$debian = 1;

			displayWelcome($updateMode);

			$packages = `dpkg -l | grep ii`;
			$deplist = "";
			$depcheck = 0;
	
			foreach($ubuntu_deps as $dep)
			{		

				$depquote = preg_quote($dep);
	
				if(!preg_match("/$depquote/", $packages))
				{
					if(strstr($dep, "ii  ")!=null)
					{
						$dep = trim($dep, "ii  ");
					}
			
					if(strstr($dep, "mysql") != null)
					{
						system('touch .mysqlrestart');
						$mysqlrestart = 1;
					}
	
					
					if (preg_match('/^php5-/', $dep))
					{
						if (extension_loaded(str_replace('php5-', '', $dep)))
						{
							continue;
						}	
					}		
			
					$deps[$dep] = $dep;
					fwrite(STDOUT, " * Missing $dep\n");
					$deplist .= "$dep ";
					$depcheck++;
					if($dep == 'php5-mysql')
					{
						system('touch .mysqlrestart');
						$mysqlrestart = 1;
					}
				}
			}
	
			if($depcheck > 0)
			{
				if (!isset($args['install']))
				{
					$a = strtolower(prompt("Install missing dependencies automatically? [Y/n]", "Y"));
				}
				else
				{
					$a = 'y';
				}
			
				if ($a == 'y' || $a == 'yes')
				{
					fwrite(STDOUT, "\n\033[1;32mInstalling Packages \033[0;39m\n-------------------\n");
					fwrite(STDOUT, "\nInstalling missing packages via the system 'apt-get' installer, please standby\nthis process make take several minutes depending the speed of your network\n\n");
	
					foreach($deps as $dep)
					{
						$deplist .= $dep . " ";
					}
			
					system("apt-get -y install $deplist");
	
					fwrite(STDOUT, "\n");
			
					// Check packages again
					$packages = `dpkg -l`;
					$faildep = "";
			
					foreach($deps as $dep)
					{
						$depquote = preg_quote($dep);
						if(preg_match("/$depquote/", $packages))
						{
							fwrite(STDOUT, " * Installed successfully: $dep\n");	
						}
						else
						{
							fwrite(STDOUT, " * Failed install: $dep\n");
							$faildep++;
						}
					}
	
					if($faildep)
					{
						fwrite(STDOUT, "\n\nCould not successfully install the missing dependencies, please check your connection to the\nnetwork is active and the system 'apt-get' command is installed correctly\n\n");
	
						if (!isset($args['install']))
						{
							prompt('[Press Enter to Continue]');
						}	
					}
					else
					{
						fwrite(STDOUT, "\nMissing dependencies successfully installed, proceeding with Atmail configuration.\n");
	
						if (!isset($args['install']))
						{
							prompt('[Press Enter to Continue]');
						}	
					}
					$restart_b = true;
				}
			}
			else
			{
				fwrite(STDOUT, "* All Dependencies are correctly installed.\n");
			}
			// End Ubuntu 9.10 requirements
		}
	}

	// Check Debian requirements
	// If we are running a system with apt-get, install the requirements
	//check for ReadyNAS debian version first - has very tight deps
	$isReadyNAS = false;
	$uname = `uname -r`;
	if( strpos($uname, '.RNx86') )
		$isReadyNAS = true;
	
	if( $isReadyNAS && file_exists('/etc/debian_version') && !file_exists('/etc/lsb-release') )
	{
		displayWelcome($updateMode);
	
		$packages = `dpkg -l | grep ii`;
		$deplist = "";
		$depcheck = 0;

		foreach( $readynas_deps as $dep )
		{		

			$depquote = preg_quote($dep);

			if( !preg_match("/$depquote/", $packages) )
			{
				//trim ii   used to more accurately match from the dpkg results
				if( strstr($dep, "ii  ")!=null )
					$dep = trim($dep, "ii  ");

				if( strstr($dep, "mysql") != null )
				{

					system('touch .mysqlrestart');
					$mysqlrestart = 1;

				}


				if( preg_match('/^php5-/', $dep) && extension_loaded(str_replace('php5-', '', $dep)) )
						continue;

				$deps[$dep] = $dep;
				fwrite(STDOUT, " * Missing $dep\n");
				$deplist .= "$dep ";
				$depcheck++;
				if($dep == 'php5-mysql')
				{
					system('touch .mysqlrestart');
					$mysqlrestart = 1;
				}
			}
		}

		if($depcheck > 0)
		{
			if (!isset($args['install']))
				$a = strtolower(prompt("Install missing dependencies automatically? [Y/n]", "Y"));
			else
				$a = 'y';

			if ($a == 'y' || $a == 'yes')
			{

				fwrite(STDOUT, "\n\033[1;32mInstalling Packages \033[0;39m\n-------------------\n");
				fwrite(STDOUT, "\nInstalling missing packages via the system 'apt-get' installer, please standby\nthis process make take several minutes depending the speed of your network\n\n");

				foreach($deps as $dep)
					$deplist .= $dep . " ";

				system("apt-get -y install $deplist");

				fwrite(STDOUT, "\n");

				// Check packages again
				$packages = `dpkg -l`;
				$faildep = "";

				foreach($deps as $dep)
				{
					$depquote = preg_quote($dep);
					if(preg_match("/$depquote/", $packages))
						fwrite(STDOUT, " * Installed successfully: $dep\n");	
					else
					{
						fwrite(STDOUT, " * Failed install: $dep\n");
						$faildep++;
					}
				}

				if($faildep)
				{
					fwrite(STDOUT, "\n\nCould not successfully install the missing dependencies, please check your connection to the\nnetwork is active and the system 'apt-get' command is installed correctly\n\n");

					if (!isset($args['install']))
						prompt('[Press Enter to Continue]');
				}
				else
				{
					fwrite(STDOUT, "\nMissing dependencies successfully installed, proceeding with Atmail configuration.\n");

					if (!isset($args['install']))
						prompt('[Press Enter to Continue]');
				}
				$restart_b = true;
			}
		}
		else
			fwrite(STDOUT, "* All Dependencies are correctly installed.\n");
		// End ReadyNAS requirements
	
	
	}
	
	if( !$isReadyNAS && (file_exists('/etc/debian_version') || file_exists('/etc/debian_release')) && !file_exists('/etc/lsb-release'))
	{
		$debian = 1;

		displayWelcome($updateMode);
	
		$packages = `dpkg -l | grep ii`;
		$deplist = "";
		$depcheck = 0;
	
		foreach($debian2_deps as $dep)
		{		

			$depquote = preg_quote($dep);
	
			if(!preg_match("/$depquote/", $packages))
			{
				if(strstr($dep, "ii  ")!=null)
				{
					$dep = trim($dep, "ii  ");
				}
			
				if(strstr($dep, "mysql") != null)
				{
					system('touch .mysqlrestart');
					$mysqlrestart = 1;
				}
	
					
				if (preg_match('/^php5-/', $dep))
				{
					if (extension_loaded(str_replace('php5-', '', $dep)))
					{
						continue;
					}	
				}		
			
				$deps[$dep] = $dep;
				fwrite(STDOUT, " * Missing $dep\n");
				$deplist .= "$dep ";
				$depcheck++;
				if($dep == 'php5-mysql')
				{
					system('touch .mysqlrestart');
					$mysqlrestart = 1;
				}
			}
		}
	
		if($depcheck > 0)
		{
			if (!isset($args['install']))
			{
				$a = strtolower(prompt("Install missing dependencies automatically? [Y/n]", "Y"));
			}
			else
			{
				$a = 'y';
			}
			
			if ($a == 'y' || $a == 'yes')
			{
				fwrite(STDOUT, "\n\033[1;32mInstalling Packages \033[0;39m\n-------------------\n");
				fwrite(STDOUT, "\nInstalling missing packages via the system 'aptitude' installer, please standby\nthis process make take several minutes depending the speed of your network\n\n");
	
				foreach($deps as $dep)
				{
					$deplist .= $dep . " ";
				}
			
				system("aptitude -y install $deplist");
	
				fwrite(STDOUT, "\n");
			
				// Check packages again
				$packages = `dpkg -l`;
				$faildep = "";
			
				foreach($deps as $dep)
				{
					$depquote = preg_quote($dep);
					if(preg_match("/$depquote/", $packages))
					{
						fwrite(STDOUT, " * Installed successfully: $dep\n");	
					}
					else
					{
						fwrite(STDOUT, " * Failed install: $dep\n");
						$faildep++;
					}
				}
	
				if($faildep)
				{
					fwrite(STDOUT, "\n\nCould not successfully install the missing dependencies, please check your connection to the\nnetwork is active and the system 'aptitude' command is installed correctly\n\n");
	
					if (!isset($args['install']))
					{
						prompt('[Press Enter to Continue]');
					}	
				}
				else
				{
					fwrite(STDOUT, "\nMissing dependencies successfully installed, proceeding with Atmail configuration.\n");
	
					if (!isset($args['install']))
					{
						prompt('[Press Enter to Continue]');
					}	
				}
				$restart_b = true;
			}
		}
		else
		{
			fwrite(STDOUT, "* All Dependencies are correctly installed.\n");
		}
		// End Debian requirements
	}

	// If we are running a system with yum, prompt to install any missing packages
	if(file_exists("/etc/redhat-release") && file_exists("/usr/bin/yum") || file_exists("/etc/fedora-release") && file_exists("/usr/bin/yum"))
	{
		$opSystem = getOperatingSystemInfo();
		displayWelcome($updateMode);
		
		$packages = `rpm -qa`;
		$deplist = "";
		$depcheck = 0;
		if ($opSystem['version'] >= 6)
		{
			$redhat_deps = array_merge(array('perl-ExtUtils-MakeMaker'), $redhat_deps);
		}

		foreach( $redhat_deps as $dep )
		{

			$depquote = preg_quote($dep);
				
			if(!preg_match("/^$depquote/m", $packages))
			{
				if(strstr($dep, "-2")!=null)
				{

					$dep = trim($dep, "-2");

				}
			
				if (preg_match('/^php-/', $dep))
				{
					if (extension_loaded(str_replace('php-', '', $dep)))
					{

						continue;

					}	

				}
				$deps[$dep] = $dep;
				fwrite(STDOUT, " * Missing $dep\n");
				$deplist .= "$dep ";
				$depcheck++;
			
				if($dep == 'mysql')
				{
				
					system('touch .mysqlrestart');
					$mysqlrestart = 1;
				
				}   
			
			}  
		}
	
		if($depcheck > 0)
		{
			if (!isset($args['install']))
			{
				$a = strtolower(prompt("Install missing dependencies automatically? [Y/n]", "Y"));
			}
			else
			{
				$a = 'y';
			}
		
			if ($a == 'y' || $a == 'yes')
			{
				fwrite(STDOUT, "\n\033[1;32mInstalling Packages \033[0;39m\n-------------------\n");
				fwrite(STDOUT, "\nInstalling missing packages via the system 'yum' installer, please standby\nthis process make take several minutes depending the speed of your network\n\n");

				foreach($deps as $dep)
				{
					system("yum -y install $dep 2>&1");
				}
	
				//Make sure MySQL is started and does so on boot as we may have just started it
				system("/etc/init.d/mysqld start");
				system("chkconfig mysqld on");
	
				// Check packages again
				$packages = `rpm -qa`;
				$faildep = "";
				foreach($deps as $dep)
				{
					//ignore php-dom - complains until php session restarted - can prob safely proceed without checking else will have to restart server-install.php
					$depquote = preg_quote($dep);
					if(preg_match("/$depquote/", $packages) )
					{
						fwrite(STDOUT, " * Installed successfully: $dep\n");
					}
					elseif( $dep == 'php-dom' )
					{
					
						fwrite(STDOUT, " * Unable to detected without restart: $dep (Should be safe to proceed if showed as successful above, else CTRL-C this install and restart it to re-detect)\n");
					
					}
					else
					{
						fwrite(STDOUT, " * Failed install: $dep\n");
						$faildep++;
					}
				}
	
				if($faildep)
				{
			
					fwrite(STDOUT, "\n\nCould not successfully install the missing dependencies, please check your connection to the\nnetwork is active and the system 'yum' command is installed correctly\n\nSee KB article: http://atmail.com/view_article.php?num=822 for further details.\n");
	
					if( !isset($args['install']) )
					{
			
						exit;
			
					}	
			
				}
				elseif( !isset($args['updatecli']) )
				{                            
				
					$restartInstaller = true;
			
				}
			
			}	
		}
		else
		{

			fwrite(STDOUT, "* All Dependencies are correctly installed.\n");

		}
	}

	// Debian, restart installer if php5-mysql missing
	if ($mysqlrestart)
	{

		fwrite(STDOUT, "\nMissing PHP mysql module installed, however you must re-run the installation script to initialize PHP correctly\n");
		fwrite(STDOUT, "Please run:\n\nphp server-install.php\nTo continue installation\n\n");
		exit(1); //will exit kill the installer or just the include?

	}

	// Restart installer if deps installed
	if( $restartInstaller )
	{

		fwrite(STDOUT, "\nMissing PHP modules installed, however you must re-run the installation script for the installer to detect and utilise the new modules\n");
		fwrite(STDOUT, "Please run:\n\nphp server-install.php\nTo continue installation\n\n");
		exit(1);
	
	}
	fwrite(STDOUT, "\n");
}
