# -*- coding: utf-8 -*-  

import uuid
import socket
import fcntl
import struct
import common
import os
import commands
from logrecord import LogRecord
from PyQt4.QtCore import QString
import globalvariable

#得到本机的MAC地址
def get_mac_address(): 
    mac=getMacByEthName("br0")
    return mac
    
#print get_mac_address()    
#得到网卡的名称
# def getEthName():
#     mac = get_mac_address()
#     ethContent = os.popen('ifconfig | grep -i "%s"'%mac).readlines()
#     # return ethContent[0][0:4]
#     return "eno16777736"

#得到网卡的名称
def getEthNameList():
    ethList = []
    commandsOutput = commands.getstatusoutput("ls /sys/class/net/")
    if commandsOutput[0] == 0:
        ethList = [name for name in commandsOutput[1].split("\n") if name != "lo" and name != "virbr0" and name != "br0"]
    return ethList

#根据网卡名称活动相应的MAC值
def getMacByEthName(ethName):
    macValue = None
    commandsOutput = commands.getstatusoutput("cat /sys/class/net/%s/address" % ethName)
    if commandsOutput[0] == 0:
        macValue = commandsOutput[1]
        return macValue
    return macValue

#得到本机的IP地址
def get_ip_address_():
    ethNameList = getEthNameList()
    ethNameList = ["br0"]
    if not ethNameList:
        LogRecord.instance().logger.info(u"获取网卡名称失败！")
        return

    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    return socket.inet_ntoa(fcntl.ioctl(
        s.fileno(),
        0x8915,  # SIOCGIFADDR
        struct.pack('256s', ethNameList[0][:15])
    )[20:24])
def get_ip_address():
    #ethName = "br0"
    #if 
    if getLinuxOperationSystemType().find("Ubuntu") == -1:
        ifcmd = "ifconfig br0 |grep inet"
    else:
        ifcmd = "ifconfig eth0 |grep inet"
        
    status = commands.getstatusoutput(ifcmd)
    if status[0] == 0:
        output = QString(status[1]).trimmed().split(" ")
    else:
        output = []
    for i in range(len(output)):
        if output[i] == "inet":
            return str(output[i+1])
        
    return "0.0.0.0"


#获取本机网关
def get_netmask_gateway_dns():
    netmask = gateway = DNS_first = ""

    ethName = common.DEFAULT_NETCARD_NAME
    ethNameList = getEthNameList()
    if not ethNameList:
        LogRecord.instance().logger.info(u"获取网卡名称失败！")
    else:
        ethName = ethNameList[0]

    netConfigFile = common.NETWORK_CONFIG_CENTOS_7_0 + "br0"

    statusOutput = commands.getstatusoutput("cat %s" % netConfigFile)
    if statusOutput[0] == 0:
        outputList = QString(statusOutput[1]).split("\n")
        for value in outputList:
            if value.split("=")[0] == "NETMASK":
                netmask = str(value.split("=")[1])
            elif value.split("=")[0] == "GATEWAY":
                gateway = str(value.split("=")[1])
            elif value.split("=")[0] == "DNS1":
                DNS_first = str(value.split("=")[1])
        
    return [netmask, gateway, DNS_first]

#获取本机网络类型
def get_network_type():
    netType = None
    ethName = common.DEFAULT_NETCARD_NAME
    ethNameList = getEthNameList()
    if not ethNameList:
        LogRecord.instance().logger.info(u"获取网卡名称失败！")
    else:
        ethName = ethNameList[0]

    netConfigFile = common.NETWORK_CONFIG_CENTOS_7_0 + "br0"

    statusOutput = commands.getstatusoutput("cat %s" % netConfigFile)
    if statusOutput[0] == 0:
        output = QString(statusOutput[1])
        if output.contains("dhcp"):
            netType = "dhcp"
        else:
            netType = "static"
            
    return netType
    

#根据虚拟机的名称从虚拟机列表中找到该名称的虚拟机所有信息
def getVMInfoFromVMS(vmsInfoList, name):
    vmInfo = {}
    for subInfo in vmsInfoList:
        if subInfo["name"] == name:
            vmInfo = subInfo
            
    return vmInfo
    
#从云主机广播的信息中根据本机的MAC值来提取分配给该学生机的云桌面名称
def getVMCloudsNameFromBroadInfo(data):
    contentList = data.split("||")
    length = len(contentList)
    mac = get_mac_address()
    vmName = None
    for i in range(length):
        if contentList[i].split(",")[0] == mac:
            vmName = contentList[i].split(",")[1]
            break
        
    return vmName

#从云主机广播的信息中根据本机的MAC值来提取分配给该学生机的classid
def getInfoVMCloudsNameFromBroad(data):
    contentList = data.split("||")
    classid = None
    if len(contentList)>=2:
        cmd = contentList[0]
        classid = contentList[1]
    return classid
        
#设置计算机的名称
def setStuentPCName(pcName):
    cmdDelete = "sed -i /HOSTNAME/d /etc/sysconfig/network"
    cmdAppend = "sed -i '$ a\\HOSTNAME=%s' /etc/sysconfig/network" % pcName
    cmd = cmdDelete + "&&" + cmdAppend
    if os.system(cmd) != 0:
        return False
    
    return True
    
#获得版本号和版本日期
def getVersionAndReleaseDate():
    version = None
    rDate = None
    if os.path.exists("/etc/default/version"):
        statusOutput = commands.getstatusoutput("cat /etc/default/version")
        if statusOutput[0] == 0:
            outputList = QString(statusOutput[1]).split("\n")
            for value in outputList:
                if value.split("=")[0] == "VERSION":
                    version = value.split("=")[1]
                if value.split("=")[0] == "BUILD_DATE":
                    rDate = value.split("=")[1]
                    
    return version, rDate
                    

#得到当前屏幕支持的分辨率列表
def getScreenResolution():
    """得到屏幕支持的分辨率"""
    rowStartNumber = QString();
    rowStopNumber = None
    
    #获得显示器名称，连接状态及行号
    cmd = "xrandr | awk '{ if($2 ~ \"connected\") {print $1 \" \" $2 \" \" NR}}'";

    statusOutput = commands.getstatusoutput(cmd)
    monitorList = statusOutput[1].split("\n")
    Monitors = [i for i in monitorList if not i.startswith("xrandr")]

    #根据组合列表把显示器名称和支持的分辨率放入到一个字典中
    resolutionMap = {}
    count = len(Monitors)
    for i in range(count):
        monitorName = Monitors[i].split(" ")[0]
        linkStatus = Monitors[i].split(" ")[1]
        rowStartNumber = Monitors[i].split(" ")[2]
        
        if linkStatus == "disconnected" or monitorName == "xrandr:":
            continue
 
        if i != count - 1:
            rowStopNumber = Monitors[i+1].split(" ")[2]
  
        resolutionCmd = QString()
#             if rowStopNumber.isEmpty() or rowStopNumber.isNull():
        if rowStopNumber is None:
            resolutionCmd = "xrandr | awk '{ if(NR > " + rowStartNumber + ")" + "{print $1}}'"
        else:
            resolutionCmd = "xrandr | awk '{ if((NR > " + rowStartNumber + ") && (NR < " + rowStopNumber + "))" + "{print $1}}'"
  
#             resolutionList = self.getCmdExecValue(resolutionCmd)
        
        statusOutput = commands.getstatusoutput(resolutionCmd)
        resolutionList = statusOutput[1].split("\n")
        resolutionList = [i for i in resolutionList if not i.startswith("xrandr")]
        
        resolutionMap[monitorName] = resolutionList
          
    return resolutionMap

def setUbuntuDynamicNetwork():
        """设置动态网络的信息到配置文件"""
        delCmd = "sed -i '/auto eth0/,$'d %s" % common.NETWORK_CONFIG_UBUNTU
        delOk = os.system(delCmd)
        content = "auto eth0\\niface eth0 inet dhcp\\ndns-nameservers Empty Empty"
        addCmd = "sed -i '$ a\\%s' %s" % (content, common.NETWORK_CONFIG_UBUNTU)
        addOk = os.system(addCmd)
        if delOk != 0 or addOk != 0:
            return False
        return True

def setUbuntuStaticNetwork(params):
        """设置静态网络的信息到配置文件"""
        delCmd = "sed -i '/auto eth0/,$'d %s" % common.NETWORK_CONFIG_UBUNTU
        delOk = os.system(delCmd)

        IPADDR = params[1].strip()
        NETMASK = params[2].strip()
        if len(IPADDR) == 0 or len(NETMASK) == 0:
           return False
        GATEWAY = params[3].strip()
        DNS = params[4].strip()

        content = None

        if not GATEWAY:
            content = "auto eth0\\niface eth0 inet static\\naddress %s\\nnetmask %s" % (IPADDR, NETMASK)
        else:
            content = "auto eth0\\niface eth0 inet static\\naddress %s\\nnetmask %s\\ngateway %s" % (IPADDR, NETMASK, GATEWAY)

        #如果是指定DNS地址
        if DNS:
            content = "%s\\ndns-nameservers %s" % (content, DNS)

        addCmd = "sed -i '$ a\\%s' %s" % (content, common.NETWORK_CONFIG_UBUNTU)
        addOk = os.system(addCmd)
        if delOk != 0 and addOk != 0:
            return False
        return True    
    
def setDynamicNetwork():
    """设置动态网络的信息到配置文件"""
    if QString(getLinuxOperationSystemType()).contains("Ubuntu"):
        return setUbuntuDynamicNetwork()
		
    if not os.path.exists("/etc/sysconfig/network-scripts/"):
        os.system("mkdir -p /etc/sysconfig/network-scripts")
    if not os.path.exists("/etc/sysconfig/network-scripts/ifcfg-br0"):
        os.mknod("/etc/sysconfig/network-scripts/ifcfg-br0")
        
    delBrCmd = "echo > /etc/sysconfig/network-scripts/ifcfg-br0"
    content = "BOOTPROTO=dhcp\\nDEVICE=br0\\nONBOOT=yes\\nTYPE=Bridge\\nPEERNTP=yes\\ncheck_link_down(){\\n    return 1; \\n}"
    addCmd = "sed -i '$ a\\%s' /etc/sysconfig/network-scripts/ifcfg-br0" % (content)
    delOk = os.system(delBrCmd)
    addOk = os.system(addCmd)
    
    os.system(str("persist /etc/sysconfig/network-scripts/ifcfg-br0"))

    if delOk != 0 or addOk != 0:
        return False

    return True

def setStaticNetwork(params):
    """设置静态网络的信息到配置文件"""
    if QString(getLinuxOperationSystemType()).contains("Ubuntu"):
        return setUbuntuStaticNetwork(params)
    if not os.path.exists("/etc/sysconfig/network-scripts/"):
        os.system("mkdir -p /etc/sysconfig/network-scripts")
    if not os.path.exists("/etc/sysconfig/network-scripts/ifcfg-br0"):
        os.mknod("/etc/sysconfig/network-scripts/ifcfg-br0")
    delCmd = "echo > /etc/sysconfig/network-scripts/ifcfg-br0"
    IPADDR = params[1].strip()
    NETMASK = params[2].strip()

    if len(IPADDR) == 0 or len(NETMASK) == 0:
        return False

    GATEWAY = params[3].strip()
    DNS = params[4].strip()

    content = None
    delOk = os.system(delCmd)
    
    if GATEWAY:
        content = "DEVICE=br0\\nONBOOT=yes\\nTYPE=Bridge\\nBOOTPROTO=static\\nIPADDR=%s\\nNETMASK=%s\\nGATEWAY=%s" % (IPADDR, NETMASK, GATEWAY)
    else:
        content = "DEVICE=br0\\nONBOOT=yes\\nTYPE=Bridge\\nBOOTPROTO=static\\nIPADDR=%s\\nNETMASK=%s" % (IPADDR, NETMASK)

    if DNS:
        content = "%s\\nDNS1=%s" % (content, DNS)

    #addCmd = "sed -i '$ a\\%s' /config/etc/sysconfig/network-scripts/ifcfg-%s" % (content, ethNameList[0])
    addCmd = "sed -i '$ a\\%s' /etc/sysconfig/network-scripts/ifcfg-br0" % (content)
    addOk = os.system(addCmd)
    
    os.system(str("persist /etc/sysconfig/network-scripts/ifcfg-br0"))

    if delOk != 0 and addOk != 0:
        return False

    return True

def getLinuxOperationSystemType():
    """得到linux操作系统的类型"""
    statusOutput = commands.getstatusoutput("head -n 1 /etc/issue")
    LogRecord.instance().logger.info(u"/etc/issue文件内容：%s" % statusOutput[1])
    if statusOutput[0] == 0:
        output = QString(statusOutput[1])
        if output.contains("Ubuntu 12.04"):
            return "Ubuntu 12.04"
        if output.contains("Ubuntu 13.04"):
            return "Ubuntu 13.04"
        elif output.contains("CentOS release 6.5"):
            return "CentOS 6.5"
        elif output.contains("CentOS release 7.0"):
            return "CentOS 7.0"
        elif output.contains("Ubuntu 14.04"):
            return "Ubuntu 14.04"
        elif output.contains("Ubuntu"):
            return "Ubuntu"
        elif output.contains("MCOS-cClassroom-student"):
            return "CentOS 7.0"
        elif output.contains("CentOS"):
            return "CentOS"
        else:
            return "CentOS"

    return None


def getProgramRunningEnvType():
    """判断程序执行的环境类型"""
    if os.path.exists("/config"):
        return common.DEVELOPED_ENV_TYPE
        #return common.OPERATION_ENV_TYPE
    else:
        return common.DEVELOPED_ENV_TYPE


def convertPathToVarPath(localPath):
    """转换路径到/var类型下的路径"""
    return localPath

def convertPathToConfigPath(localPath):
    """转换路径到/config类型下的路径"""
    if localPath.startswith("/usr"):
        return localPath.replace("/usr", "/config/usr")
    elif localPath.startswith("/etc"):
        return localPath.replace("/etc", "/config/etc")


def umountFile(filePath):
    if os.system("umount %s" % filePath) != 0:
        LogRecord.instance().logger.info(u"卸载配置文件失败，文件路径:%s" % filePath)

def mountFile(filePath):
    mountPath = convertPathToConfigPath(filePath)
    if os.system("mount --bind %s %s" % (mountPath, filePath)) != 0:
        LogRecord.instance().logger.info(u"挂载配置文件失败，挂载路径:%s, 配置文件路径:%s" % (mountPath, filePath))
        
        