<?php

include dirname(__FILE__) . '/../nfc-bootloader.php';
include 'Atmail/Dav/Migrator.php';
include 'Atmail/Update/Utils.php';

init_set('memory_limit', -1);
init_set('max_execution_time', -1);
set_time_limit(0);

sabmig_displayWelcome();

/* defaults */
$dataDir = '/usr/local/atmail/calendarserver/server/twistedcaldav/atmail/data/calendars/__uids__/';
$dryRun = false;
$logLevel = Atmail_Dav_Migrator::LOG_ERROR;

$arguments = $argv;
array_shift($arguments);

foreach($arguments as $key=>$arg) {
    if (strpos($arg,'-')===0) {

        switch($arg) {

            case '--dry-run' :
                $dryRun = true;
            break;
            case '-v' :
                $logLevel = Atmail_Dav_Migrator::LOG_INFO;
                break;
            case '-vv' :
                $logLevel = Atmail_Dav_Migrator::LOG_DEBUG;
                break;
            default :
            {
            	sabmig_displayUsage();
                die('Unknown option: ' . $arg . "\n");
			}
        }

    } else {
        $dataDir = $arg;
    }

}

$db = Zend_Registry::get('dbAdapter');
$db->getConnection();
if(count($db->query('select * from principals')->fetchAll()) > 0)
{
        echo "A migration attempt has been detected. For the migration to succeed, we will need to remove current data.\n";
        echo "ALL CURRENT ATMAIL 6 CALENDAR SQL DATA WILL BE LOST.\n";
        if( prompt('Would you like to clear this data and re-run the migration? ', 'yes') == 'yes')
        {
                fwrite(STDOUT, "Clearing Atmail 6 calendar sql database...\n");
                $db->query("delete from calendarDelegates");
                $db->query("delete from calendarExtendedData"); 
                $db->query("delete from calendarObjects"); 
                $db->query("delete from calendars"); 
                $db->query("delete from principals");  
        }
}

echo "Migrating calendar data to new calendar system.\n";
echo "Please be patient, this process may take a while..\n\n";

_controlServerServices(false);
_mountCalendarServer();

if(!is_dir($dataDir))
{ 
	sabmig_displayUsage();
	die("FATAL: Unable to find darwin calendar server data directory.\n" . $dataDir . "\n");
}

try
{
	$migrator = new Atmail_Dav_Migrator($dataDir);
	$migrator->dryRun = $dryRun;
	$migrator->logLevel = $logLevel;
	$migrator->start();
}
catch(Exception $e)
{
	$deathHints = "\n";
	$deathMessage = $e->getMessage();
	if($deathMessage == "could not find driver")
	{
		$deathHints = "Please ensure that the sqlite PDO driver for php is available.\n";
	}
	die("Exception caught. \n\nError: "  . $e->getMessage() . "\n" . $deathHints);
}
_mountCalendarServer(false);

echo "\n\nCompleted.\n\n";

function sabmig_displayWelcome()
{
	echo "\n\033[1;32mWelcome to the Atmail calendar migration script\033[0;39m\n";
	echo "-------------------------------------------------\n";
}

function sabmig_displayUsage()
{
	echo "\n";
	echo "Usage : " . $_SERVER["SCRIPT_FILENAME"] . " [data_directory] [-v/-vv/--dry-run]\n\n";
	echo "--dry-run : Do not actually perform writes.\n";
	echo "-v[v] : verbose or very verbose debug output.\n";
	echo "data_directory : Specify darwin data directory.\n";
	echo "\n";
}