# coding: utf-8
import os, sys, json,time

from base import *
from files_tools import *

file_read = 1179785
file_exec = 1179817
file_modify = 1245631
file_all = 2032127

# 设置文件权限和所有者（level:继承到子目录）
def set_file_access(filename, user, access, level=True):
    # 是否继承
    if level:
        if os.path.isdir(filename):
            filelist = []
            get_file_list(filename, filelist)
            for new_path in filelist:
                status, info = SetFileAccess(new_path, user, access)
                if not status: return status, info
            return True, None
        else:
            return SetFileAccess(filename, user, access)
    else:
        return SetFileAccess(filename, user, access)


# 删除文件权限
def del_file_access(filename, user):
    import win32security
    sd = win32security.GetFileSecurity(filename, win32security.DACL_SECURITY_INFORMATION)
    dacl = sd.GetSecurityDescriptorDacl()
    ace_count = dacl.GetAceCount()

    for i in range(ace_count, 0, -1):
        try:
            data = {}
            data['rev'], data['access'], usersid = dacl.GetAce(i - 1)
            data['user'], data['group'], data['type'] = win32security.LookupAccountSid('', usersid)

            if data['user'].lower() == user.lower():
                dacl.DeleteAce(i - 1)
        except:
            try:
                # 处理拒绝访问
                dacl.DeleteAce(i - 1)
            except:
                pass
    sd.SetSecurityDescriptorDacl(1, dacl, 0)
    win32security.SetFileSecurity(filename, win32security.DACL_SECURITY_INFORMATION, sd)
    return True


def SetFileAccess(filename, user, access):
    """
    设置文件权限(安装脚本使用)
    @filename 文件路径
    @user 用户名
    @access 用户权限
    """
    try:
        import win32security
        sd = win32security.GetFileSecurity(filename, win32security.DACL_SECURITY_INFORMATION)
        dacl = sd.GetSecurityDescriptorDacl()
        ace_count = dacl.GetAceCount()

        for i in range(ace_count, 0, -1):
            try:
                data = {}
                data['rev'], data['access'], usersid = dacl.GetAce(i - 1)
                data['user'], data['group'], data['type'] = win32security.LookupAccountSid('', usersid)
                if data['user'].lower() == user.lower(): dacl.DeleteAce(i - 1)  # 删除旧的dacl
            except:
                dacl.DeleteAce(i - 1)
        try:
            userx, domain, type = win32security.LookupAccountName("", user)
        except:
            try:
                userx, domain, type = win32security.LookupAccountName("", 'IIS APPPOOL\\' + user)
            except:
                return False, "【{}】用户不存在，无法设置权限。".format(user)
        if access > 0:  dacl.AddAccessAllowedAceEx(win32security.ACL_REVISION, 3, access, userx)

        sd.SetSecurityDescriptorDacl(1, dacl, 0)
        win32security.SetFileSecurity(filename, win32security.DACL_SECURITY_INFORMATION, sd)
        return True, None
    except:
        return False, get_error_info()