#!/usr/bin/python3
# -*- coding: utf-8; -*-
#
# (c) 2004-2007 Linbox / Free&ALter Soft, http://linbox.com
# (c) 2007-2012 Mandriva, http://www.mandriva.com
#
# This file is part of Mandriva Management Console (MMC).
#
# MMC is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# MMC is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with MMC; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

"""
This little tool checks for all directory users that:
 - the user's primary group exists
 - the user is a member of her/primary group
"""

from mmc.plugins.base import ldapUserGroupControl

l = ldapUserGroupControl()

users = l.searchUser()
for user in users:
    uid = user['uid']
    entry = l.getDetailedUser(uid)
    if 'gidNumber' in entry:
        pgidnumber = entry['gidNumber'][0]
        try:
            pgroup = l.getDetailedGroupById(pgidnumber)
        except UnboundLocalError:
            print(
                "Warning user %s: Primary group with this GID number doesn't exist: %s" %
                (uid, pgidnumber))
            continue
        gname = pgroup['cn'][0]
        try:
            members = pgroup['memberUid']
        except KeyError:
            members = []
        if uid not in members:
            c = input(
                'User "%s" is not a member of her/his primary group "%s". Fix it ? (y/n) ' %
                (uid, gname))
            if c in ['y', 'Y']:
                print('Fixing user entry')
                l.addUserToGroup(gname, uid)
            else:
                print('NOT fixing user entry')
