<?php

include dirname(__FILE__) . '/../nfc-bootloader.php';

ini_set('memory_limit', -1);
ini_set('max_execution_time', -1);
set_time_limit(0);

$username = $argv[1];
$password = $argv[2];

echo "Testing calendar ldap authentication using :\nUSERNAME:" . $username . "\nPASSWORD:" . $password . "\n";


$ldapOptionsMapping = array(
    'ldap_host' => 'host',
    'ldap_basedn' => 'baseDn',
    'ldap_bindauthdn' => 'bindAuthDn'
);

$results = Zend_Registry::get('config')->dovecot;
print_r($results);
$ldapOptions = array();
foreach($results as $key => $result)
{
    if(array_key_exists($key, $ldapOptionsMapping))
    {
        $ldapOptions[$ldapOptionsMapping[$key]] = $result;
    }
}


$baseDnParts = explode('dc=', strtolower($ldapOptions['baseDn']));
$ldapOptions['accountDomainName'] = '';
$ldapOptions['accountDomainNameShort'] = '';

foreach($baseDnParts as $baseDnPart)
{
    if($baseDnPart == '') continue;
    $baseDnPart = trim($baseDnPart, ',');
    if($ldapOptions['accountDomainNameShort'] == '')
    {
        $ldapOptions['accountDomainNameShort'] = strtoupper($baseDnPart);
    }
    $ldapOptions['accountDomainName'] .= $baseDnPart . ".";
}
$ldapOptions['accountDomainName'] = trim($ldapOptions['accountDomainName'], '.');

list($account, $domain) = explode('@', $username);
$bindAuthDn = str_replace('%n', $account, str_replace('%u', $username, $ldapOptions['bindAuthDn']));
unset($ldapOptions['bindAuthDn']);
echo ('WEBDAV : ldapOption in use : ' . print_r($ldapOptions, true) . "\n");
echo ('WEBDAV : bindAuthDn : ' . $bindAuthDn . ' / ' . $password . "\n");
$ldap = new Zend_Ldap($ldapOptions);
print_r($ldap);

$var = $ldap->bind($bindAuthDn, $password);
print_r($var);
//$atmailLdap = new Atmail_Ldap($username, Zend_Registry::get('config')->dovecot);
//$ldapOptions = $atmailLdap->ldapOptions();

//echo "CURRENT LDAP OPTION ARRAY:\n";
//print_r($ldapOptions);
/*
$ldap = new Zend_Ldap($ldapOptions);
echo "CURRENT ZEND LDAP OBJECT:\n"; 
print_r($ldap); 

echo "Attempting BIND....\n";
$var = $ldap->bind($atmailLdap->bindAuthDn, $password);
print_r($var);

*/