<?php
/*
* Copyright (c) 2009-2010 ATMAIL. All rights reserved
* See http://atmail.com/license.php for license agreement
*/

/**
 * Migrate users from the IMAP server to user Maildirs on this server
 * Usage
 * php migrate-imap.php < list-of-users.csv
 *
 * Where list-of-users contains :
 * username,password,domain,mailserver,download-all-folders
 * ben,mypass,atmail.nl,mail.atmail.nl,0
 * Any number of users , each separated by a newline.
 *
 * The download-all-folders by default is zero; and will only download the users subscribed
 * messages via IMAP ( recommended ) Set download-all-folders to 1 to download all
 * folders on the remote IMAP server including unsubscribed folders
 *
 * -i will switch on interactive mode so that you can see more progress information on the migration
 */

function printError( $string )
{
	
	fwrite(STDOUT, "\033[1;31m" . $string . "\033[0;39m\n");
	
}   

function printSuccess( $string )
{
	
	fwrite(STDOUT, "\033[1;32m" . $string . "\033[0;39m\n");
	
}   

function printWarning( $string )
{
	
	fwrite(STDOUT, "\033[1;33m" . $string . "\033[0;39m\n");
	
}   

ini_set('memory_limit', "64M");
error_reporting(E_ALL & ~E_NOTICE);

// Display the welcome message
$msg = <<<EOF

\033[1;32mWelcome to Atmail Batch IMAP User Migration script\033[0;39m
----------------------------------

This script will accept a CSV file as input and 
batch migrate IMAP user account from a remote server 
to this server, copying folders and messages.

EOF;
fwrite(STDOUT, $msg);

// Make sure we are running as root
$ps = shell_exec("ps aux | grep 'php .*batch-migrate-imap.php'");

if (preg_match("/^(.+?)\s+.+?php .*?batch-migrate-imap\.php/m", $ps, $m))
{
    if (trim($m[1]) != 'root')
        exit( __FILE__ . " must be run as root. Please su to root, and consult the migration details for further information.\n\n");
}
else
{

    fwrite(STDOUT, "\nCould not detect what user batch-migrate-imap.php is running as. If you are not running the migration as root please do so.\n");

}


while( ( $line = fgetcsv(STDIN, 10000, ",") ) !== FALSE )
{

	
	//list($user, $pass, $domain, $imapserver, $allfolders) = array_map('trim', $line);
	//prepare each arg for shell exec
	foreach( $line as $k => $v )
	{
	
		$line[$k] = escapeshellarg($line[$k]);
	
	}    
	$singleLine = implode(' ', $line);
	
	// Skip blank lines
	if ( is_null($line[0]) || count($line) < 5 )
	{
	
		printError("Unable to find user record while processing current input\n" . $singleLine . "\nTrying to continue." );
		continue;
	
	}

    printSuccess("Processing next line: " . $singleLine );
	$cmd = escapeshellcmd('php migrate-imap.php ' . $singleLine);
	passthru($cmd);

}

echo "Done.\n";