<?php
/*
* Copyright (c) 2009-2010 ATMAIL. All rights reserved
* See http://atmail.com/license.php for license agreement
*/
/**
 * Migrate SquirrelMail address book to Atmail 6.x.x
 *
 * @author Brad Kowalczyk <brad@staff.atmail.com>
 */
 
define('SCRIPT_USAGE_MSG', "usage: php migrate-squirrelmail-abook.php [squirrelmail_database_name] [sql_username:sql_password] [sql_hostname(optional)]\n");

// get squirrelmail database details
$dbname = $_SERVER['argv'][1];
list($sqluser, $sqlpass) = explode(':', $_SERVER['argv'][2]);
$sqlhost = ($_SERVER['argv'][3]) ? $_SERVER['argv'][3] : 'localhost';

// Check for correct command useage
if (empty($dbname) || empty($sqluser)) {
	fwrite(STDOUT, "Please specify the database name and sql username for accessing the SquirrelMail addressbook\n");
	fwrite(STDOUT, SCRIPT_USAGE_MSG);
	exit;
}

require_once("../../nfc-bootloader.php");

// setup SquirrelMail DB connection
$sqDb = Zend_Db::Factory('Pdo_Mysql', array(
    'host'     => $sqlhost,
    'username' => $sqluser,
    'password' => $sqlpass,
    'dbname'   => $dbname)
);

// Check that the specified database exists and can be connected to
try {
    $sqDb->getConnection();    
} catch (Exception $e) {
    fwrite(STDOUT, "There was an error connecting to '$dbname', please details and try again:\n\n$e\n\n");
    fwrite(STDOUT, SCRIPT_USAGE_MSG);
    exit;
}

// Check for squirrelmail address table
if (!in_array('address', $sqDb->listTables())) {
    fwrite(STDOUT, "It appears the database specified ($dbname) may not be the squirrelmail database,\nthe table 'address' could not be found...\n");
    fwrite(STDOUT, "Please specify the database name for the SquirrelMail addressbook\n");
    fwrite(STDOUT, SCRIPT_USAGE_MSG);
    exit;
}

// OK lets grab the squirrelmail data
$owner = $sqDb->fetchCol("select owner from `address` group by owner");

$sqDb->setFetchMode(Zend_Db::FETCH_OBJ);

foreach ($owner as $own) {

	$own = strtolower($own);

	// Get each unique email from the abook
	fwrite(STDOUT, "Viewing records for $own ...\n");
	$emails = $sqDb->fetchCol("select email from `address` where owner=? group by email", array($own));

	foreach ($emails as $email) {

		if (empty($email))
            continue;

		$row = $sqDb->fetchRow("select * from `address` where owner=? and email=?", array($own, $email));

		// Insert the entry into the DB
		$abook = new contacts( array('Account' => $own) );
		$args = array(
		    'contact' => array(
		        'UserFirstName' => $row->firstname,
		        'UserLastName'  => $row->lastname,
		        'UserEmail'     => $row->email
		    )
		);
		
		$id = $abook->addContact($args);

		if (is_numeric($id))
	        fwrite(STDOUT, "Added '{$row->firstname} {$row->lastname}' <{$row->email}>\n");
	    else
	        fwrite(STDOUT, "ERROR adding '{$row->firstname} {$row->lastname}' <{$row->email}>\n");
	    
	    unset($abook);
	}
}

fwrite(STDOUT, "SquirrelMail address book migration complete.\n");
