#!/usr/bin/python
from invirt.database import *
from invirt.config import structs as config
import sys
import getafsgroups
import subprocess

def expandLocker(name):
    try:
        groups = getafsgroups.getLockerAcl(name)
    except getafsgroups.AfsProcessError, e:
        if e.message.startswith("fs: You don't have the required access rights on"):
            return []
        elif e.message.endswith("doesn't exist\n"):
            # presumably deactivated
            return []
        else:
            raise
    cell = getafsgroups.getCell(name)
    ans = set()
    for group in groups:
        if ':' in group:
            ans.update(getafsgroups.getAfsGroupMembers(group, cell))
        else:
            ans.add(group)
    return ans

def isUser(name):
    p = subprocess.Popen(['vos', 'examine', 'user.'+name],
                         stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    if p.wait():
        return False
    return True
    

def expandName(name):
    if ':' not in name:
        if isUser(name):
            return [name]
        return []
    try:
        return getafsgroups.getAfsGroupMembers(name, config.authz[0].cell)
    except getafsgroups.AfsProcessError:
        return []

def accessList(m):
    people = set()
    people.update(expandLocker(m.owner))
    if m.administrator is not None:
        people.update(expandName(m.administrator))
    return people

def refreshMachine(m):
    people = accessList(m)
    old_people = set(a.user for a in m.acl)
    for removed in old_people - people:
        ma = [x for x in m.acl if x.user == removed][0]
        session.delete(ma)
    for p in people - old_people:
        ma = MachineAccess(user=p)
        m.acl.append(ma)
        session.save_or_update(ma)
    
def refreshCache():
    session.begin()

    try:
        machines = Machine.query().all()
        for m in machines:
            refreshMachine(m)
        session.flush()
            
        # Atomically execute our changes
        session.commit()
    except:
        # Failed! Rollback all the changes.
        session.rollback()
        raise

if __name__ == '__main__':
    connect()
    refreshCache()
