#!/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

class AfsProcessError(Exception):
    pass

def getAfsGroupMembers(group, cell):
    subprocess.check_call(['aklog', cell], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    p = subprocess.Popen(["pts", "membership", "-encrypt", group, '-c', cell],
                         stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    err = p.stderr.read()
    if err: #Error code doesn't reveal missing groups, but stderr does
        if err.startswith('pts: Permission denied ; unable to get membership of '):
            return []
        raise AfsProcessError(err)
    return [line.strip() for line in p.stdout.readlines()[1:]]

def getLockerPath(locker):
    if '/' in locker or locker in ['.', '..']:
        raise AfsProcessError("Locker '%s' is invalid." % locker)
    return '/mit/' + locker

def getCell(locker):
    p = subprocess.Popen(["fs", "whichcell", getLockerPath(locker)], 
                         stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    if p.wait():
        raise AfsProcessError(p.stderr.read())
    return p.stdout.read().split()[-1][1:-1]

def getLockerAcl(locker):
    p = subprocess.Popen(["fs", "listacl", getLockerPath(locker)], 
                         stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    if p.wait():
        raise AfsProcessError(p.stderr.read())
    lines = p.stdout.readlines()
    values = []
    for line in lines[1:]:
        fields = line.split()
        if fields[0] == 'Negative':
            break
        if 'a' in fields[1]:
            values.append(fields[0])
    return values

def notLockerOwner(user, locker):
    """
    notLockerOwner(user, locker) returns false if and only if user administers locker.

    If the user does not own the locker, returns the string reason for
    the failure.
    """
    try:
        cell = getCell(locker)
        values = getLockerAcl(locker)
    except AfsProcessError, e:
        return str(e)

    for entry in values:
        if entry == user or (entry[0:6] == "system" and
                                user in getAfsGroupMembers(entry, cell)):
            return False
    return "You don't have admin bits on " + getLockerPath(locker)


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