<?php

/**
 * Import IMail users from csv file into Atmail6
 *
 * csv format as created by migrate-imail.pl:
 * server (ignored),username, password, domain, subadmin, ?
 *
 * @author Brad Kowalczyk
 */
 
require_once("../../nfc-bootloader.php");
 
// Migrate data dump from Imail into @Mail
$dir = $_SERVER['argv'][1];
$admin = $_SERVER['argv'][2];

if (!$dir || !$admin) {
	print "Usage: php migrate-abook.php [directory] [admin-username]\n";
	print "Where [directory] contains the directory of the Imail data dump output.\n";
	print "Where [admin-username] is the username for the Atmail master WebAdmin user.\n";
	exit;
}

require_once('application/models/api.php');
$_SERVER['PHP_AUTH_USER'] = $_SERVER['argv'][2];
$api = new api( array('directApi' => 1) );

$dh = opendir("$dir/") or die("Cannot opendir $dir/\n");


while (false !== $domain = readdir($dh)) {

	if ($domain == "." || $domain == ".." || !preg_match("/[a-z0-9\-.]+\.[a-z]/i", $domain))
	   continue;
	processDomainAbooks($domain, $dir);
}

// All Done
fwrite(STDOUT, "Congratulations. Abook Data migration complete!\n");


function processDomainAbooks($domain, $dir)
{
    if (is_dir("$dir/$domain/users")) {
        $dir = "$dir/$domain/users";    
    } elseif (is_dir("$dir/$domain/Users")) {
        $dir = "$dir/$domain/Users";
    } else {
        return;
    }
    
    if (!$dh2 = opendir($dir)) {
        return;    
    }
    
    while (false !== $user = readdir($dh2)) {
        if ($user == "." || $user == ".." || !is_dir("$dir/$user")) {
            continue;    
        }
        
        processUsersAbook("$user@$domain", "$dir/$user");
    }
}


function processUsersAbook($account, $dir)
{
    $dbAdapter = Zend_Registry::get('dbAdapter');
    $account = strtolower($account);
    
    fwrite(STDOUT, "Checking $account for an address book...\n");
    
    if (!$dbAdapter->fetchOne("select 1 from Users where Account=?", array($account))) {
		fwrite(STDOUT, "$account does not exist on the system, please verify\n");
		return;
	}
	
    if (file_exists("$dir/aliases.txt")) {
        $file = "aliases.txt";
    } elseif (file_exists("$dir/Aliases.txt")) {
        $file = "Aliases.txt";
    } else {
        fwrite(STDOUT, "aliases.txt/Aliases.txt does not exist for $account, perhaps they have no addressbook\n");
        return;    
    }
    
    if (!$fh = fopen("$dir/$file", 'r')) {
        fwrite(STDOUT, "Could not open {$account}'s $file for reading, check permissions. Skipping...\n");
        return;
    }
    		
	while (false !== $line = fgets($fh)) {

	    $line = trim($line);

        $firstname = '';
        $lastname = '';
        $email = '';
        
		if (preg_match('/("(.*?)")?\s*<(.*?)>/', $line, $m)) {
   			$email = $m[3];
   			$name = $m[2];

   			//$name = str_replace(',', '', $name);

			if (preg_match('/^([a-z]+),?\s+([a-z]+)$/', $name, $m2)) {
				$firstname = $m2[1];
				$lastname = $m2[2];
			} else {
				$firstname = $name;
			}
            
            if ($dbAdapter->fetchOne("select 1 from Abook where UserEmail = ? and Account = ?", array($email, $account)) != '1') {
       			fwrite(STDOUT, "Adding into abook for $account:\n firstname: $firstname\nlastname: $lastname\nemail: $email\n---------------------------------------------------\n");
                $dbAdapter->query("insert into Abook (UserEmail, UserFirstName, UserLastName, Account) values (?,?,?,?)", array($email, $firstname, $lastname, $account));
            } else {
                fwrite(STDOUT, "Skipping adding $email as they already exist in abook for $account...\n");
            }
		}
	}
}

