<?php
/**
 * Use this script to perform an Atmail version update without having to
 * use webadmin.
 * 
 * php webmail-update.php
 */

require_once(dirname(__FILE__) . '/../nfc-bootloader.php');
//require_once('Atmail/Update.php');

$updater = new Atmail_Update_Db($dbAdapter);

$stamp = date('Ymd-H:i:s');

// set the log file for this update attempt (trunc)
$updater->setLogFile(rtrim(APP_ROOT . 'log', '/') . '/atmail.update.' . $stamp . '.log');

//first check if new update code has already been unpacked over old code
$versionCurrentDBSchema = generateVersionString(Zend_Registry::get('config')->global['version'], true);
$versionCurrentLocalCodebase = generateVersionString(getVersionCurrentLocalCodebase(), true);
$versionOrig = $versionCurrentDBSchema;

// ***** USE THE NEW UPDATER HERE ******
try
{
	$cliRequired = $updater->updateAll();
}
catch(Exception $e)
{
	// some sort of error.
	$error = true;
	$updater->log('Database update ran into issues while trying to update to ' . generateVersionString($versionCurrentLocalCodebase, true) . "\n" . "Error details : " . $e->getMessage() . "\nPlease see " . $updater->getLogFile() . " for more further details.");
	fwrite(STDERR, 'Database update ran into issues while trying to update to ' . generateVersionString($versionCurrentLocalCodebase, true) . "\n" . "Error details : " . $e->getMessage() . "\nPlease see "  . $updater->getLogFile() . " for more further details.");
}

$versions[] = $versionCurrentLocalCodebase;

$versionCurrentDBSchema = generateVersionString($dbAdapter->fetchOne("select keyValue from Config where keyName = 'version'"), true);

/* end db schema changes */
if( !$error && version_compare($versionCurrentDBSchema, $versionCurrentLocalCodebase, '==' ) )
{
	fwrite(STDOUT, 'Database schema update complete.');
	
	if( $cliRequired )
	{
		$cliUpdater = APP_ROOT . "utilities/update/client-update.php";
		fwrite(STDOUT, "\nRunning $cliUpdater\n");
		`php $cliUpdater`;
        fwrite(STDOUT, "\n\nNOTE: If the Atmail system consists of multiple webmail servers please now run "php $cliUpdater" on all other servers\n\n");
	} else {
        fwrite(STDOUT, "\nAtmail update complete!\n");
    }

}
else if(!$error)
{
	$error = true;
	fwrite(STDERR, 'Database update did not complete. Current version: ' . generateVersionString($versionCurrentDBSchema, true) . ' Available version: ' . generateVersionString($versionCurrentLocalCodebase, true) . "\nPlease see "  . $updater->getLogFile() . " for more details.");
}

// Close the dialog-box on the update window
if($error)
{
	fwrite(STDERR, "\nUpdate Atmail - Failed\n");	
}
