<?php
/**
 * @category 	Atmail
 * @package 	Models
 * @subpackage	Appliance
 * @copyright 	Copyright (c) 2009-2011 ATMAIL. All rights reserved
 * @license 	See http://atmail.com/license.php for license agreement
 * @author		Ben Duncan ben@staff.atmail.com
 * @author		Atmail (http://atmail.com)
 */

class appliance
{
	/*
	Load the system IP, hostname and network configuration directly. Don't trust the vales in the Config
	array/DB, just in case an admin has changed the settings via the terminal/SSH
	*/
	public static function loadNetworkSettings($array)
	{
	
	// Find current IP's
	$eth0 = `/sbin/ifconfig eth0`;
	if (preg_match('/inet addr:(.*?) /', $eth0, $m))
        $array['ipeth0'] = $m[1];

	if (preg_match('/Mask:(.*)/', $eth0, $m))
        $array['networketh0'] = $m[1];

	$eth1 = `/sbin/ifconfig eth1`;
	if (preg_match('/inet addr:(.*?) /', $eth1, $m))
        $array['ipeth1'] = $m[1];

	if (preg_match('/Mask:(.*)/', $eth1, $m))
        $array['networketh1'] = $m[1];

	// Find the default route
	$droute = `/bin/netstat -nr`;

	if (preg_match('/^0\.0\.0\.0\s+(.*?)\s.*?eth0/m', $droute, $m))	{
        $array['defaultgatewayeth0'] = $m[1];
	}

	if (preg_match('/^0\.0\.0\.0\s+(.*?)\s.*?eth1/m', $droute, $m)) {
        $array['defaultgatewayeth1'] = $m[1];
	}

	// Find the default nameserver
	if ($fh = fopen('/etc/resolv.conf', 'r')) {

		$nameservers = array();

    	while(false !== $line = fgets($fh))	{
            $line = trim($line);
    		if (preg_match('/nameserver (.*)/', $line, $m)) {		
				array_push($nameservers, $m[1]);
    		}
    	}

		$array['nameserver1'] = $nameservers[0];
		
		if(isset($nameservers[1]))
		$array['nameserver2'] = $nameservers[1];

		if(isset($nameservers[2]))
		$array['nameserver3'] = $nameservers[2];

    	fclose($fh);
	} else {
	    print "Cannot open /etc/resolv.conf\n";
	}

	$array['ipconfeth0'] = '';
	$array['ipconfeth1'] = '';
	$array['peerdns'] = true; //peerdns field only relevant when at least one interface has DHCP enabled
	
	// Check if a device is DHCP and if using PEERDNS
	if ($fh = fopen('/etc/sysconfig/network-scripts/ifcfg-eth0', 'r')) 
	{

		
		while( false !== $line = fgets($fh) )
		{

			if( strpos(strtoupper($line), 'BOOTPROTO=DHCP') !== false )
				$array['ipconfeth0'] = 'DHCP';
			
			if( strpos(strtoupper($line), 'PEERDNS=NO') !== false )
				$array['peerdns'] = false;

		}
		fclose($fh);

	}

	if( $fh = fopen('/etc/sysconfig/network-scripts/ifcfg-eth1', 'r') )
	{
	
		while( false !== $line = fgets($fh) )
		{
		
			if( strpos(strtoupper($line), 'BOOTPROTO=DHCP') !== false )
				$array['ipconfeth1'] = 'DHCP';
			
			if( strpos(strtoupper($line), 'PEERDNS=NO') !== false )
				$array['peerdns'] = false;

		}
		fclose($fh);

	}

	// Find the servers hostname
	$array['hostname'] = trim(`/bin/hostname`);	
	return $array;
}

	/* Restart the network services using the setuid root script */
	public static function restartNetworkSettings()
	{
	
		system('/usr/local/atmail/mailserver/bin/atmail-restart-network > /dev/null 2>&1');
    	
		return;
		
	}
	
	public static function saveNetworkSettings($array)
	{
		$config = '';
		
		// Save the settings
		if ($array['save'])	{

			system('/bin/hostname ' . escapeshellarg($array['hostname']));
			//$pref['hostname'] = $var['hostname'];
			//writeconf();

			// Write the /etc/init.d/network with the new hostname
			if (!$read = @fopen("/etc/sysconfig/network", 'r'))
	            catcherror("Cannot read /etc/init.d/network");

	        while(!feof($read))
	        {
	            $line = fgets($read);
				$line = preg_replace('/HOSTNAME=.*/', "HOSTNAME={$array['hostname']}", $line);
				$config .= $line;
			}

			fclose($read);

			if (!$write = @fopen("/etc/sysconfig/network", 'w'))
			catcherror("Cannot write /etc/sysconfig/network");

			fwrite($write, $config);
			fclose($write);

			foreach(array('eth0', 'eth1') as $int) {

				// If we are DHCP
				if ( $array["ipconf$int"] == 'DHCP' )	
				{
					if ($fh = fopen("/etc/sysconfig/network-scripts/ifcfg-$int", 'w')) 
					{
						fwrite($fh, "BOOTPROTO=dhcp\nTYPE=Ethernet\nDEVICE=$int\nONBOOT=yes\n");
						//if peerdns = no then also write in the static specified namesrevers
						if( array_key_exists('peerdns',$array) && $array['peerdns'] == false )
						{
							fwrite($fh, "PEERDNS=no\n");
							if ($array['nameserver1'])
								fwrite($fh, "DNS1=" . $array['nameserver1'] . "\n");
							if ($array['nameserver2'])
								fwrite($fh, "DNS2=" . $array['nameserver2'] . "\n");
							if ($array['nameserver3'])
								fwrite($fh, "DNS3=" . $array['nameserver3'] . "\n");
							
						}
						fclose($fh);
					}
					else
						print "Cannot write: /etc/sysconfig/network-scripts/ifcfg-$int\n";


				}
				else
				{
					// Manually configure interface
					if ($fh = fopen("/etc/sysconfig/network-scripts/ifcfg-$int", 'w')) 
					{
						fwrite($fh, "BOOTPROTO=none\nTYPE=Ethernet\nDEVICE=$int\nNETMASK=" . $array["network$int"] . "\nIPADDR=" . $array["ip$int"] . "\nGATEWAY=" . $array["defaultgateway$int"] . "\nONBOOT=yes\n");
						fclose($fh);
					}
					else
						print "Cannot write: /etc/sysconfig/network-scripts/ifcfg-$int\n";

				}
			}

			// Sleep after config write, ifconfig/hostname seem to have a lag
			//sleep(2);
			
			// Change the nameservers (should only be done if DHCP not used)
			//if no DHCP or DHCP but PEERDNS=no then write resolv.conf - else dhclient will continue overite it
			if( 
				   ( $array["ipconf0"] !== 'DHCP' && $array["ipconf1"] !== 'DHCP' ) 
				|| ( array_key_exists('peerdns',$array) && $array['peerdns'] == false ) 
			)
			{
				
				if ($fh = fopen( APP_ROOT . "config/resolv.conf.tmp", 'w')) 
				{
				
					fwrite($fh, "; generated by Atmail Server\n");
					if ($array['nameserver1'])
						fwrite($fh, "nameserver {$array['nameserver1']}\n");
					if ($array['nameserver2'])
						fwrite($fh, "nameserver {$array['nameserver2']}\n");
					if ($array['nameserver3'])
						fwrite($fh, "nameserver {$array['nameserver3']}\n");
					fclose($fh);

				}
				
				//seems like we need a restart of network settings because shutting down an DHCP intercate with PEERDNS=yes will cause removal of all nameservers in current resolve.conf
				self::restartNetworkSettings();
				system('/usr/local/atmail/mailserver/bin/atmail-move-resolv > /dev/null 2>&1');
				
				//update motd and issue with latest URLs
				#Atmail reset server permissions also rewrites /etc/issue and /etc/motd with latest IP addresses
				$array = self::loadNetworkSettings( array() );
				$URLs = "\nhttp://" . $array['ipeth0'] . "/\n" . ($array['ipeth1'] ? "http://" . $array['ipeth1'] . "/\n" : '');
				file_put_contents("/etc/issue", "CentOS 6 (Atmail Appliance)\nKernel \\\r on an \\\m\n\nTo manage the Atmail appliance visit one of network interface URLs: $URLs\n");
				file_put_contents("/etc/motd", "Welcome to the Atmail Server Appliance\n\nTo manage the Atmail appliance visit one of network interface URLs: $URLs\n-------------------------------------\n\nFor technical support please consult:\nhttp://support.atmail.com/\n");

			}
			self::restartNetworkSettings();
		
		}

	}                                               

}