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

/**
 * Migrate Config from Atmail 5.x to Atmail 6.x system
 *
 */
if ($_SERVER['argc'] < 2) 
{

    die("usage: php migrate-a5-config.php [A5 Config.php]\n");    

}


include_once $_SERVER['argv'][1];
if( !isset($pref) )
{

    die("Please supply correct path to valid Config.php\n");

}

//APP_ROOT must be calculated globally for the entire application (no matter where it is launched from) as ../webmail/
define('APP_ROOT', dirname(dirname(dirname(__FILE__))) . DIRECTORY_SEPARATOR); //N.B. APP_ROOT already contains trailing slash
set_include_path(APP_ROOT . "library/" . PATH_SEPARATOR . APP_ROOT . "library/Atmail" . PATH_SEPARATOR . APP_ROOT . PATH_SEPARATOR . get_include_path());

require_once 'Zend/Loader/Autoloader.php';
$loader = Zend_Loader_Autoloader::getInstance();
//$loader->registerNamespace('App_'); //for model namespacing
$loader->setFallbackAutoloader(true);
$loader->suppressNotFoundWarnings(false);

$migratePref['serverDir'] = dirname(APP_ROOT) . DIRECTORY_SEPARATOR; //normally /usr/local/atmail/

// Write the new DB settings
try 
{


	$dbConfig = new Zend_Config_Ini(APP_ROOT . 'config/dbconfig.ini', 'production');
	
} 
catch( Exception $e )
{
	
	die("unable to find now dbconfig.ini at (" . APP_ROOT . "config/dbConfig.ini), check required previous migration steps");
	
}
$migratePref['sql_host'] = $dbConfig->database->params->host;
$migratePref['sql_user'] = $dbConfig->database->params->username;
$migratePref['sql_pass'] = $dbConfig->database->params->password;
$migratePref['sql_table'] = $dbConfig->database->params->dbname;

// Exim config values
foreach(array('smtp_load_queue',
	'virus_enable',
	'dkim_enable',
	'dkim_enable_outbound',
	'tlssmtp',
	'tlssmtp_remote',
	'smtp_throttle',
	'smtp_auth',
	'filter_max_bodysize',
	'virus_scanner',
	'virus_msg',
	'split_spool_directory',
	'smtp_load_reserve',
	'queue_run_in_order',
	'smtp_enforce_sync',
	'smtp_load_queue_delivery',
	'smtp_max_rcpt',
	'queue_run_max',
	'remote_max_parallel',
	'smtp_max_connections_perip',
	'smtp_verify_senders',
	'smtp_max_connections',
	'smtp_popimaprelay_timeout',
	'crypt',
	'mail_group_support',
	'smtp_popimaprelay',
	'filter_sa_enable',
	'max_msg_size',
	'filter_required_hits',
	'filter_required_hits_reject',
	'filter_subject_tag',
	'filter_spam_treatment',
	'filter_trusted_networks',
	'filter_skip_trusted',
	'filter_attach_check',
	'filter_blocked_attachments',
	'filter_uridns_support',
	'filter_spf_support',
	'filter_awl_support',
	'filter_bayes_auto_learn_threshold_nonspam',
	'filter_bayes_auto_learn_threshold_spam',
	'filter_bayes_min_ham_num',
	'filter_use_bayes',
	'filter_rbl_support',
	'filter_rbl_servers',
	'filter_awl_purge_low',
	'filter_awl_purge_medium',
	'filter_awl_purge_high'
	) as $config ) 
{
		
	if( isset($pref[$config]) )
	{ 
		
		$migrateExim[$config] = $pref[$config];
		
	}
		
}

// Dovecot values
	$migrateDovecot['default_domain'] = $pref['default_domain'];
	$migrateDovecot['dovecot_max'] = $pref['imap_max'] + $pref['pop3_max'] + '30';	// Dovecot limit, add extra for Webmail requests

// Pref values
foreach(array(
	'footer_msg',
	'brandname',
	'company_url',
	'smtphost',
	'smtpauth_password',
	'smtpauth_username',
	'session_timeout',
	'admin_email',
	'log_purge_days'
	) as $config) 
{

	if( isset($pref[$config]) )
	{ 
		
		$migratePref[$config] = $pref[$config];
		
	}
	
}

// allowed_mailservers
	$migratePref['remoteServers'] = str_replace(",", "\n", $pref['allowed_mailservers']);
	$migratePref['remoteDomains'] = str_replace(",", "\n", $pref['allowed_domains']);
	
// Restrict to remoteServers or remoteDomains if defined
if( $pref['allowed_mailservers'] ) 
{

	$migratePref['remoteServersOverwrite'] = "0";	

}

if( $pref['allowed_domains'] ) 
{

	$migratePref['remoteDomainsOverwrite'] = "0";	

}

// Remove pop3 from mail_type
	$migratePref['mail_type'] = str_replace('pop3', '', $pref['mail_type']);
	if(empty($migratePref['mail_type']))
		$migratePref['mail_type'] = 'imapssl';

// Migrate Shared/Groupware settings
if( empty($pref['GlobalAbook']) )
{

	$migratePref['sharedAbook'] = 0;
	$migratePref['groupwareenable'] = 'off';
	
// If "domain wide"
}
elseif( $pref['GlobalAbook'] == '1' )
{

	$migratePref['sharedAbook'] = '2';
	$migratePref['groupwareenable'] = 'system';
	
// If "Site wide"
}
elseif( $pref['GlobalAbook'] == '2' )
{
	$migratePref['sharedAbook'] = '1';
	$migratePref['groupwareenable'] = 'system';
	
}

// Default config values
foreach( array('UserQuota',
	'TimeZone',
	'MsgNum',
	'DateFormat',
	'TimeFormat'
	) as $config) 
{
	
		if( isset($settings[$config]) )
		{ 

			$migrateDefaults[$config] = $settings[$config];

		}
}

fwrite(STDOUT, "Writing Configuration values.\n");

Zend_Registry::set('dbConfig', $dbConfig);

$dbAdapter = Zend_Db::Factory($dbConfig->database);
$dbAdapter->query("SET NAMES 'utf8'");
Zend_Db_Table::setDefaultAdapter($dbAdapter);
Zend_Registry::set('dbAdapter', $dbAdapter);

//Get main configuration from database
$config = new Atmail_Config_Mysql($dbConfig, true);
Zend_Registry::set('config', $config);

// Now save all collected data
require_once 'application/models/config.php';
require_once 'application/models/dbTables.php';

config::save('global', $migratePref);
config::save('defaultUserSettings', $migrateDefaults);
//config::save('plugins', $plugins);

// Only publish server config files if the installation is server-mode, not required for webmail only
if(file_exists(APP_ROOT . "../mailserver/"))
{
	
	config::save('exim', $migrateExim);
	config::save('dovecot', $migrateDovecot);

	config::publishServerConfigFiles('exim');
	config::modifyDbConfigInExistingServerConfigFiles($migratePref);		
	
}

// Setup log
$logPath = APP_ROOT . 'log' . DIRECTORY_SEPARATOR . 'atmail.log';
if ( !file_exists($logPath) ) 
{

	touch($logPath);

}

$logWriter = new Zend_Log_Writer_Stream($logPath);
$log = new Atmail_Log($logWriter);
$log->info('');
$log->info('------------------------------');
$log->info('Installation completed at: ' . time());
Zend_Registry::set('log', $log);

fwrite(STDOUT, "Migration completed.\n");