$ldap_groups = $plugin->ldap_get_grouplist();
if ($CFG->debug_ldap_groupes) {
    pp_print_object('plugin group names cache ', $plugin->groups_dn_cache);
}
foreach ($ldap_groups as $group => $groupname) {
    print "processing LDAP group " . $groupname . PHP_EOL;
    $params = array('idnumber' => $groupname);
    // not that we search for cohort IDNUMBER and not name for a match
    // thus it we do not autocreate cohorts, admin MUST create cohorts beforehand
    // and set their IDNUMBER to the exact value of the corresponding attribute in LDAP
    if (!($cohort = $DB->get_record('cohort', $params, '*'))) {
        if (empty($plugin->config->cohort_synching_ldap_groups_autocreate_cohorts)) {
            print "ignoring {$groupname} that does not exist in Moodle (autocreation is off)" . PHP_EOL;
            continue;
        }
        $ldap_members = $plugin->ldap_get_group_members($groupname);
        // do not create yet the cohort if no known Moodle users are concerned
        if (count($ldap_members) == 0) {
            print "not autocreating empty cohort " . $groupname . PHP_EOL;
            continue;
        }
        $cohort = new StdClass();
        $cohort->name = $cohort->idnumber = $groupname;
        $cohort->contextid = context_system::instance()->id;
        //$cohort->component='sync_ldap';
        $cohort->description = get_string('cohort_synchronized_with_group', 'local_ldap', $groupname);
        //print_r($cohort);
        $cohortid = cohort_add_cohort($cohort);
        print "creating cohort " . $group . PHP_EOL;
    } else {
        $cohortid = $cohort->id;