#!/usr/bin/python3

import ldap
from os import scandir

HOME = '/home'
BASE  = 'ou=schueler,ou=Benutzer,ou=fvs,ou=SCHULEN,o=ml3'
#BASE  = 'ou=Benutzer,ou=fvs,ou=SCHULEN,o=ml3'
LDAP = 'ldap://ldap.steinbeisschule-reutlingen.de'

def fetch_ou(uid):
    l = ldap.initialize(LDAP)
    f = '(uid=' + uid + ')'
    try:
        return l.search_s(BASE,ldap.SCOPE_SUBTREE,f,['ou'])[0][1]['ou'][0].decode('utf-8')
    except:
        return None

def fetch_uids(crs):
    uids = []
    l = ldap.initialize(LDAP)
    #    if 'Abgang' in crs:
    #        b = 'ou=Abgang,' + BASE
    #    else:
    #        b = 'ou=' + crs + ',' + BASE
    b = BASE
    r = l.search_s(b,ldap.SCOPE_SUBTREE,'(ou=' + crs + ')',['uid'])
    for dn,entry in r:
        if entry != {}:
            uids.append(entry['uid'][0].decode('utf-8'))
    return uids

def assign_course(user, crs_uids, home):
    c = fetch_ou(user)
    print('Needed to fetch new course', c, 'for', user)
    if c:
        crs_uids[c] = fetch_uids(c)
        home[user] = c
    else:
        print('No course for', user , 'found!')


if __name__ == '__main__':
    home = {}
    with scandir(HOME) as it:
        for entry in it:
            if entry.is_dir() and entry.name != 'lost+found':
                home[entry.name] = ''

    crs_uids = {}
    for user in home:
        if crs_uids == {}:
            assign_course(user, crs_uids, home)
            continue
        for k in crs_uids.keys():
            if user in crs_uids[k]:
                home[user] = k
                break
        else:
            assign_course(user, crs_uids, home)

    for usr in home:
        print(usr, home[usr])


    for crs in crs_uids.keys():
        print(usr, home[usr])

    for k, v in sorted(crs_uids.items()):
        print(k, sorted(v))
        for item in sorted(v):
            try:
                print(item, home[item])
            except:
                print('No home for', item, 'found.')
