<?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];

if (!$dir) {
	print "Usage: php import-users.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;
}

if (!$fh = fopen("$dir/users.txt", 'r')) {
    die("could not open $dir/users.txt!");    
}

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

$domList = $api->domainList();
$existingDomains = array();
foreach ($domList as $dom) {
    $existingDomains[] = $dom['DomainName'];    
}

$userOKcnt = 0;

while (false !== $user = fgetcsv($fh, 10000, ",")) {
    // Skip blank lines
    if (is_null($user[0])) {
        continue;
    }
    
    // Trim whitespace from start/end of values
    $user = array_map('trim', $user);

    // Skip if migrate file is invalid
    // must have username, password and domain
    if (!$user[1] || !$user[2] || !$user[3]) {
        continue;
    }
    
    // Add domain if it does not exist
    if (!in_array($user[3], $existingDomains)) {
        fwrite(STDOUT, "Adding new domain-name $user[3]...");
        $res = $api->domainCreate($user[3]);
        if (isset($res['response']['status']) && $res['response']['status'] == 'failed') {
	        fwrite(STDOUT, "ERROR: \n" . $res['response']['message'] . "\n");
	    } else {
            fwrite(STDOUT, "OK\n");
			$existingDomains[] = $user[3];
        }
    }

    // Add user
    $userData = array();
    $userData['name']             = "$user[1]@$user[3]";
    $userData['username']         = $user[1];
    $userData['Password']         = $user[2];
    $userData['Domain']           = $user[3];
    $userData['UserQuota']        = '';
    $userData['Ugroup']           = 'default';
    
    fwrite(STDOUT, "Adding user {$userData['name']}... ");

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

    // Is the account a SubAdmin user? If so append them to the Subadmin table
	if ($user[4] == 1) {
        try {
            fwrite(STDOUT, "Adding $user[1] as a Subadmin... ");
            $res = $api->subadminCreate(array('Username' => $user[1], 'Password' => $user[2]));
            if (isset($res['response']['status']) && $res['response']['status'] == 'failed') {
                fwrite(STDOUT, "ERROR: \n" . $res['response']['message'] . "\n");
                continue;
            }
            
            fwrite(STDOUT, "OK\n");
            
        } catch( Exception $e ) {
            fwrite(STDOUT, "ERROR: \n" . $e->getMessage() . "\n");		
        }
	}
}

fclose($fh);
fwrite(STDOUT, "Finished user import!\n\n");

// Migrate User-aliases
if ($fh = fopen("$dir/useraliases.txt", 'r')) {
    fwrite(STDOUT, "Starting user-alias import...\n");
    
    while (false !== $alias = fgetcsv($fh, 10000, ",")) {

        // Format follows
        // localhost,alias-name,alias-to
        
        // Skip blank lines
        if (is_null($alias[0])) {
            continue;
        }
        
        // Trim whitespace from start/end of values
        $alias = array_map('trim', $alias);
    
        // Skip if migrate file is invalid
        // must have username, password and domain
        if (!$alias[1] || !$alias[2]) {
            continue;
        }
    
    	// Add the Alias if it does not already exist
    	if (1 != $dbAdapter->fetchOne("select 1 from MailAliases where AliasName=?", array($alias[1]))) {
        	fwrite(STDOUT, "Adding alias $alias[1] -> $alias[2]\n");
        	$dbAdapter->query("insert into MailAliases (AliasName, AliasTo) VALUES(?, ?)", array($alias[1], $alias[2]));
    	}
    }
    
    fwrite(STDOUT, "User alias import complete!\n");
}

fclose($fh);

fwrite(STDOUT, "\n");

// 4: Migrate Host-aliases

if ($fh = fopen("$dir/hostaliases.txt", 'r')) {

    fwrite(STDOUT, "Starting host-alias import...\n");
    
    while (false !== $alias = fgetcsv($fh, 10000, ",")) {
    
        // Format follows
        // localhost,alias-host-name,alias-host-to
        
        // Skip blank lines
        if (is_null($alias[0])) {
            continue;
        }
        
        // Trim whitespace from start/end of values
        $alias = array_map('trim', $alias);
    
        // Skip if migrate file is invalid
        // must have username, password and domain
        if (!$alias[1] || !$alias[2]) {
            continue;
        }
            	
        // Add the Alias if it does not already exist
    	if (1 != $dbAdapter->fetchOne("select 1 from MailAliases where AliasName=?", array($alias[1]))) {
        	fwrite(STDOUT, "Adding Host-alias $alias[2] -> $alias[1]\n");
        	$dbAdapter->query("insert into MailAliases (AliasName, AliasTo) VALUES(?, ?)", array('@' . $alias[2], '@' . $alias[1]));
    	}
    }
    
    fclose($fh);

    fwrite(STDOUT, "Host alias import complete!\n");
}


// Change permissions
fwrite(STDOUT, "Changing owner on /usr/local/atmail/users to 'atmail'\n");

if (strpos(strtoupper(PHP_OS), 'WIN') !== 0) {
    system("chown -R atmail /usr/local/atmail/users");
}

// All Done
fwrite(STDOUT, "Congratulations. Data migration complete!\nMigrated $userOKcnt users\n");
