#!/usr/bin/python
import pprint
import subprocess

# import ldap
# l = ldap.open("W92-130-LDAP-2.mit.edu")
# # ldap.mit.edu is 1/2 broken right now so we're going to the working backend
# l.simple_bind_s("", "")

# def getLdapGroups(user):
#     """
#     getLdapGroups(user): returns a generator for the list of LDAP groups containing user
#     """
#     for user_data in l.search_s("ou=affiliates,dc=mit,dc=edu", ldap.SCOPE_ONELEVEL, "uid=" + user, []):
#         for group_data in l.search_s("ou=groups,dc=mit,dc=edu", ldap.SCOPE_ONELEVEL, "uniqueMember="+user_data[0], ['cn']):
#             yield group_data[1]['cn'][0]

# def checkLdapGroups(user, group):
#     """
#     checkLdapGroups(user, group): returns True if and only if user is in LDAP group group
#     """
#     for result_data in l.search_s("ou=affiliates,dc=mit,dc=edu", ldap.SCOPE_ONELEVEL, "uid=" + user, []):
#         if l.search_s("ou=groups,dc=mit,dc=edu", ldap.SCOPE_ONELEVEL, "(&(cn=" + group + ")(uniqueMember="+result_data[0] + "))", []) != []:
#             return True
#     return False

def checkAfsGroup(user, group, cell):
    """
    checkAfsGroup(user, group) returns True if and only if user is in AFS group group in cell cell
    """
    p = subprocess.Popen(["pts", "membership", group, '-c', cell], 
                         stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    if p.wait():
        return False
    for line in p.stdout.readlines()[1:]:
        if line.strip() == user:
            return True
    return False

def checkLockerOwner(user, locker, verbose=False):
    """
    checkLockerOwner(user, locker) returns True if and only if user administers locker
    """
    p = subprocess.Popen(["fs", "whichcell", "/mit/" + locker], 
                         stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    if p.wait():
        if verbose:
            return p.stderr.read()
        return False
    cell = p.stdout.read().split()[-1][1:-1]
    p = subprocess.Popen(["fs", "listacl", "/mit/" + locker], 
                         stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    if p.wait():
        if verbose:
            return p.stderr.read()
        return False
    for line in p.stdout.readlines()[1:]:
        entry = line.split()
        if not entry or entry[0] == "Negative":
            break
        if entry[1] == "rlidwka":
            if entry[0] == user or (entry[0][0:6] == "system" and 
                                    checkAfsGroup(user, entry[0], cell)):
                return True
    if verbose:
        return "You don't have admin bits on /mit/" + locker
    return False


if __name__ == "__main__":
#    print list(getldapgroups("tabbott"))
    print checkAfsGroup("tabbott", "system:debathena", 'athena.mit.edu')
    print checkAfsGroup("tabbott", "system:debathena", 'sipb.mit.edu')
    print checkAfsGroup("tabbott", "system:debathena-root", 'athena.mit.edu')
    print checkAfsGroup("tabbott", "system:hmmt-request", 'athena.mit.edu')
    print checkLockerOwner("tabbott", "tabbott")
    print checkLockerOwner("tabbott", "debathena")
    print checkLockerOwner("tabbott", "sipb")
    print checkLockerOwner("tabbott", "lsc")
    print checkLockerOwner("tabbott", "scripts")
    print checkLockerOwner("ecprice", "hmmt")
