#!/usr/bin/php
<?php
require __DIR__.'/../../vendor/autoload.php';

use nur\ldap\app\LdapApplication;
use nur\ldap\LdapObject;

LdapApplication::run(new class extends LdapApplication {
  const ARGS = [
    "merge" => parent::ARGS,
    ["-a", "--action", "args" => 1],
  ];

  protected $action;
  protected $args;

  function main() {
    if ($this->config === null) $this->config = __DIR__.'/admin.ldapconf';
    $conn = $this->getConn();

    switch ($this->action) {
    case "search": # sélection
    case "s": # sélection
      $pouet = $conn->first("", ["filter" => ["uid" => "pouet"]]);
      if ($pouet !== null) {
        Txx("trouvé", $pouet->array());
      } else {
        Txx("pas trouvé");
      }
      break;
    case "create": # création
    case "c": # création
      $pouet = new LdapObject();
      $pouet->merge([
        "objectClass" => [
          "top",
          "account",
          "simpleSecurityObject",
        ],
        "uid" => "pouet",
        "userPassword" => "plouf",
      ]);
      $pouet->initDn("dc=univ-reunion,dc=fr", "uid", $conn);
      $pouet->update(null, $conn);
      Txx("créé");
      break;
    case "modify": # modification
    case "m": # modification
      $pouet = $conn->first("uid=pouet");
      if ($pouet !== null) {
        $pouet["userPassword"] = "pass".random_int(1, 1000);
        Txx("userPassword: $pouet[userPassword]");
        $pouet->update(null, $conn);
        Txx("mis à jour");
      } else {
        Txx("pas trouvé");
      }
      break;
    case "delete": # suppression
    case "d": # suppression
      $pouet = $conn->first("uid=pouet");
      if ($pouet !== null) {
        Txx("trouvé", $pouet->array());
        $pouet->delete(null, $conn);
        Txx("supprimé");
      } else {
        Txx("pas trouvé");
      }
      break;
    }
  }
});
