<?php
 
/**
 * Migrate SquirrelMail address book to Atmail 6.x.x
 * using a directory with dumps of each user's abook
 * data
 *
 * @author Brad Kowalczyk <brad@staff.atmail.com>
 */
 
define('SCRIPT_USAGE_MSG', "usage: php migrate-from-files.php [path-to-data-dir] [admin-username] [migrate-as-external-accounts (optional)]\n");

$dataDir = $_SERVER['argv'][1];

// Check for correct command useage
if (empty($dataDir) || !isset($_SERVER['argv'][2])) {
	fwrite(STDOUT, SCRIPT_USAGE_MSG);
	exit;
}

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

//Error reporting
error_reporting(E_ALL & ~E_NOTICE);
ini_set('display_startup_errors', 1);
ini_set('display_errors', 1);

// Lets give the script some ram!
ini_set('memory_limit', -1);

// remove php time limit
set_time_limit(0);

if (!$dir = opendir($dataDir)) {
    die("Could not open $dir\n");
}

$migrate = new Migrate;

while (false !== $file = readdir($dir)) {
    
    switch (strrchr($file, ".")) {   
        case ".abook": $migrate->migrateAbook("$dataDir/$file"); break;
        case ".sig" : $migrate->migrateSig("$dataDir/$file"); break;
    }
}

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


class Migrate {
    
    private $_createdUsers = array();
    private $_api;
    
    
    public function __construct()
    {
        require_once('application/models/api.php');
        $_SERVER['PHP_AUTH_USER'] = $_SERVER['argv'][2];
        $this->_api = new api( array('directApi' => 1) );
    }
    
    
    public function migrateAbook($file)
    {
        if (!$fh = fopen($file, "r")) {
            fwrite(STDERR, "could not open $file\n");
            return;
        }
        
        while (false !== $line = fgetcsv($fh, 4096, "|")) {
            if (!isset($line[3]) || empty($line[3])) {
                continue;
            }
            
            $account = preg_replace("/\.abook$/", "", basename($file));
            
            $this->createAccount($account);
            
            // Insert the entry into the DB
    		$abook = new contacts(array('Account' => $account));
    		$args = array(
    		    'contact' => array(
                    'UserFirstName' => $line[1],
                    'UserLastName'  => $line[2],
                    'UserEmail'     => $line[3]
    		    )
    		);
    		
    		$id = $abook->addContact($args);
    
    		if (is_numeric($id))
    	        fwrite(STDOUT, "Added '{$line[1]} {$line[2]}' <{$line[3]}>\n");
    	    else
    	        fwrite(STDOUT, "ERROR adding '{$line[1]} {$line[2]}' <{$line[3]}>\n");
    	    
    	    unset($abook);
        }
    }


    public function migrateSig($file)
    {
        $account = preg_replace("/\.sig$/", "", basename($file));
        $this->createAccount($account);
        
        $sig = file_get_contents($file);
        
        $db = Zend_Registry::get("dbAdapter");
        $db->query("update UserSettings set Signature = ? where Account = ?", array($sig, $account));
    }


    public function createAccount($account)
    {        
        $account = trim($account);
        
        if (in_array($account, $this->_createdUsers)) {
            return;
        }
        
        $this->_createdUsers[] = $account;
        
        list($user, $domain) = explode("@", $account);
        
        // Add user
        $userData = array();
        $userData['name']             = $account;
        $userData['isExternalUser']   = $_SERVER['argv']['3'];
        $userData['username']         = $user;
        $userData['Domain']           = $domain;
        $userData['UserQuota']        = '';
        $userData['Ugroup']           = 'Default';

        fwrite(STDOUT, "Adding user $account... ");
    
    	try {
    	    $res = $this->_api->userCreate($userData);
    	    if (isset($res['response']['status']) && $res['response']['status'] == 'failed') {
    	        fwrite(STDOUT, "ERROR: \n" . $res['response']['message'] . "\n");
    	        return;
    	    }
    	    
    	    fwrite(STDOUT, "OK\n");
    	    $userOKcnt++;		
    	} catch( Exception $e ) {
            fwrite(STDOUT, "ERROR: " . $e->getMessage() . "\n");
            return;
    	}
    }
    
}   
