#!/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
    """
    print user, group
    p = subprocess.Popen(["pts", "membership", group, '-c', cell], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    p2 = subprocess.Popen(["grep", "-v", "^Members"], stdin=p.stdout, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    if p2.wait():
        return False
    for member in p2.stdout.read().split():
        if member == user:
            return True
    return False

def checkLockerOwner(user, locker):
    """
    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()):
        return False
    cell = p.stdout.read().split()[-1][1:-1]
    p = subprocess.Popen(["fs", "listacl", "/mit/" + locker], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    p2 = subprocess.Popen(["grep", "^  .* rlidwka$"], stdin=p.stdout, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    if (p2.wait()):
        return False
    for line in p2.stdout.read().split('\n'):
        entry = line.split()
        if 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
    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")
