<?php
class Admin_ApplianceController extends Zend_Controller_Action 
{
	
	public function init()
	{
	    $this->view->addHelperPath('library/Atmail/View/Helper/', 'Atmail_View_Helper');
	    $this->_helper->pluginCall('initAdminController', $this);
		//TODO: extend authentication to support multiple user levels/roles/groups 
		$this->view->baseUrl = $this->_request->getBaseUrl();
		$this->view->appBaseUrl = $this->_request->getBaseUrl() . (strpos($this->_request->getBaseUrl(),'index.php')?'':'/index.php');
		$this->view->siteBaseUrl = Zend_Registry::get('siteBaseUrl');
		$this->view->moduleBaseUrl = $this->view->appBaseUrl . ($this->view->requestParams['module']=='default'?'':'/' . $this->view->requestParams['module']);
		$this->view->global = Zend_Registry::get('config')->global;
		
		require_once 'application/models/admin.php';
		
		$this->admin = new admin();
		
		if ($this->_request->action == 'index' )
			return;
		// check is an XML request or not only allow index to be rendered normally (i.e. full page load)
		//if ( !$this->getRequest()->isXmlHttpRequest())
		//	throw new Atmail_Mail_Exception('Illegal call to Json handler');
		$this->_helper->viewRenderer->setNoRender();
		if( !isset($this->view->errors) )    
			$this->view->errors = array();
		if( !isset($this->view->notices) )    
			$this->view->notices = array();
	 	if( !isset($this->view->jsonIdsToRender) )    
			$this->view->jsonIdsToRender = array();
		require_once 'library/jQuery/jQuery.php'; 
		// TODO: Get the Username, Password and server API, pass to admin API
	}
	
	public function preDispatch() 
	{
		
		// Check the session is active, otherwise redirect to the login page
		$this->view->userData = $this->admin->getCurrentAdminData();
		
		if( empty($this->view->userData) ) 
		{

			$this->_forward( 'timeout', 'index', 'default' );
			return;			

		}
		
		if( $this->view->userData['UMasterAdmin'] != '1')
			throw new Exception('MasterAdmin rights required.');

		if( !file_exists("/usr/local/atmail/mailserver/bin/atmail-services-restart"))
			throw new Exception('Appliance binaries not installed');
        
		// Load a list of the admin users domain-names ( if not superuser )
		$dbAdapter = Zend_Registry::get('dbAdapter');
		$this->view->adminDomains = $dbAdapter->fetchCol("select Domain from AdminGroup where Username = " . $dbAdapter->quote($this->_session->Username));
		Atmail_Locale::setupLocaleAndTranslation( $this->view->userData['Language'] );

	}
	
	public function indexAction() 
	{
			
	}

	/* Appliance Stats */
	public function dashboardAction() {
		$dbAdapter = Zend_Registry::get('dbAdapter');
		$result = array();

		/*
		$result = $dbAdapter->select('AVG(sizeBytes)')
								->from('Log_Data', array('AVG(sizeBytes) as avgSizeBytes'))
								->query()
				   	   			->fetchAll();
		$this->view->avgSizeBytes = $result[0]['avgSizeBytes'];
		
		$q = "SELECT AVG( messagesPerDay ) AS avgMessagesPerDay FROM ( SELECT COUNT( * ) AS messagesPerDay FROM Log_Incoming GROUP BY DATE_FORMAT( dateTimeReceived, '%Y-%m-%d' ) ) AS selectMessagesPerDay";
		$result = $dbAdapter->fetchAll($q);
		$this->view->avgMessagesPerDay = $result[0]['avgMessagesPerDay']; 
		*/
		
        //$expiry = $this->_checkExpiry();
        
		$this->render('dashboard');
	}	
	/* Hardware Config Controller */

	public function networkconfigAction() {
		$this->view->fields = Zend_Registry::get('config')->network;

		// Next, load the IP/netmask/hostname settings via the system directly
		// Don't trust the DB values, refer to ifconfig/hostname
		require_once 'application/models/appliance.php';		
		$this->view->fields = appliance::loadNetworkSettings($this->view->fields);
		
		if( @file_exists( APP_ROOT . "config/.VM") )
			$this->view->isaVM = true;
		else
			$this->view->isaVM = false;

		$this->render('confignetwork');
	}

	public function networkconfigsaveAction() 
	{
	
		$request  = $this->getRequest();
		$fields = $request->fields;

		$configGlobal = Zend_Registry::get('config')->global;
		if( isset($configGlobal['demo']) &&  $configGlobal['demo'] == 1) 
		{
		
			jQuery::addMessage('Settings not saved in demo');
		    jQuery('#dialog')->dialog('close');			
			$this->render('global/jsonresponse', null, true);
			return;
		
		}

		if( isset($request->submitButton) && $request->submitButton == 'save') 
		{

			try 
			{
			
				//throw new Exception( 'testing exception error');
				require_once 'application/models/config.php';
				require_once 'application/models/appliance.php';
				config::save('network', $request->fields);
				appliance::saveNetworkSettings($request->fields); //saveNetworkSettings also restarts interfaces in special order

				//$configExim = Zend_Registry::get('config')->exim;
				//config::publishServerConfigFiles('exim');

			} 
			catch( Exception $e ) 
			{
			
				jQuery::addError( 'Failed saving config: ' . $e->getMessage() );
				jQuery('#dialog')->dialog('close');
				$this->render('global/jsonresponse', null, true);
				return;
			
			}

			if( (isset($fields['ipeth0']) && $request->ipeth0orig != $fields['ipeth0']) || (isset($fields['ipeth1']) && $request->ipeth1orig != $fields['ipeth1']) ) {
				//written this way for wase of reading
				//if either of the ips have changed then dont remove the dialogie because is is counting down to load on the new ip
				//CONSIDER: what if user is using the eth1 ip address to access admin?		
				jQuery('#dialog')->dialog('close');	
				jQuery::addMessage('Settings Saved. Waiting for timeout');
			} else {
				jQuery('#dialog')->dialog('close');	
				jQuery::addMessage('Network settings saved');
			}
			
		}
		$this->render('global/jsonresponse', null, true);
	}

	/* Reboot Controller */
	public function rebootAction() 
	{
	
		$this->render('reboot');	
	
	}

	public function rebootsaveAction() 
	{
	
		$configGlobal = Zend_Registry::get('config')->global;
		if( isset($configGlobal['demo']) && $configGlobal['demo'] == 1 ) 
		{
		
			jQuery::addMessage('Not functional in demo');
		    jQuery('#dialog')->dialog('close');			
			$this->render('global/jsonresponse', null, true);
			return;
		
		}

		$request  = $this->getRequest();

		if( $request->type == 'restart' ) 
		{
		
			jQuery::addMessage('Services reset');
			system('/usr/local/atmail/mailserver/bin/atmail-services-restart > /dev/null 2>&1');
			jQuery('#dialog')->dialog('close');
		
		}
		elseif( $request->type == 'reboot' ) 
		{
		
			jQuery::addMessage('Reboot initiated');				
			system('/usr/local/atmail/mailserver/bin/atmail-power-restart > /dev/null 2>&1');
		
		}
		elseif( $request->type == 'shutdown' ) 
		{
		
			jQuery::addMessage( $this->view->translate('Server Shutdown in Progress<br />Please disconnect power after 3 minutes.') );
			system('/usr/local/atmail/mailserver/bin/atmail-power-shutdown > /dev/null 2>&1');
			jQuery('#dialog')->dialog('close');
		
		}

		$this->render('global/jsonresponse', null, true);

	}
	
}