# coding:utf-8
'''
Created on Sep 4, 2014
@author: root
'''
import commands
import os
import json

from PyQt4.QtCore import QDateTime, QTime, QDate, QString, QObject, QFile, QTextStream, QIODevice
from model.cfg.storeinfoparser import StoreInfoParser
import cmd


class NetCtl(QObject):
    _instance = 0
    def __init__(self, parent=None): 
        super(QObject, self).__init__(parent)      
    # 获取网卡
    def getEthList(self):  # 返回一个网卡列表
        netcardList = "".join(commands.getstatusoutput("ls /sys/class/net")[1]).split("\n")
        validNetCardList = [netcard for netcard in netcardList if netcard not in ["br0", "lo", "breth0", "virbr0-nic", "virbr0"]]
        return validNetCardList
    
    
    def setCurrentNetworkInfo(self, netName, ip, ID):  # 设置本地当前使用网络
        if (QString(netName).startsWith("dhcp")):
            s = netName + ":" + "dhcp" + ":" + ID
        else:
            s = netName + ":" + ip + ":" + ID
        StoreInfoParser.instance().setCurrentLocalNetwork(s)
        
    def getCurrentNetworkInfo(self):  # 返回本地当前使用网络
        info = StoreInfoParser.instance().getCurrentLocalNetwork()
        if info == None:
            return ""
        return info
    
    def addNetAddressItem(self, netaddress, addressType):  # 向文件中写入内容
        localNetList0 = StoreInfoParser.instance().getLocalNetworkList()
        localNetList = []
        if localNetList0:
            localNetList = json.loads(localNetList0)
        
        # 根据时间设置证书的名字
        dt = QDateTime() 
        time = QTime()
        date = QDate()
        dt.setTime(time.currentTime())
        dt.setDate(date.currentDate())
        currentDate = dt.toString("yyyy-MM-dd-hh-mm-ss")
        
        addressID = currentDate.split("-").join("") + ".id"
    
        # 网络地址类型为动态时
        if (addressType == "dhcp"):
            netCardName = netaddress["netCard"]
            content = unicode((QString("dhcp-") + netCardName), "utf-8") + ":" + netCardName + ":" + addressID
            s = content
        else:
            netName = netaddress["netName"]
            netIp = netaddress["netIp"]
            netMast = netaddress["netMast"]
            netGate = netaddress["netGate"]
            netDNS1 = netaddress["netDNS1"]
            netDNS2 = netaddress["netDNS2"]
            netCard = netaddress["netCard"]
    
            if (QString(netName).startsWith("dhcp")):
                errmsg = u"禁用以dhcp为开头的网络名称！"
                return False
            if (netGate == "..." or netGate == ""):
                netGate = "Empty"
            if (netDNS1 == "..." or netDNS1 == ""):
                netDNS1 = "Empty"
            if (netDNS2 == "..." or netDNS2 == ""):
                netDNS2 = "Empty"
            content = unicode(netName, "utf-8") + ":" + netIp + ":" + netMast + ":" + netGate + ":" + netDNS1 + ":" + netDNS2 + ":" + netCard + ":" + addressID
            s = content
            
        localNetList.append(str(s))
        StoreInfoParser.instance().setLocalNetworkList(json.dumps(localNetList, ensure_ascii=False))
        return True
    
    def toList(self, listStr):
        listT = []
        listS = "a"
        if(type(listStr) == type(listS)):
            if (listStr == "" or listStr == "None" or listStr == "[]"):
                return []
            else:
                listList = []
                list = listStr.split(",")
                for i in range(len(list)):
                    listList.append(list[i].split("'")[1])
                return listList
        elif(type(listStr) == type(listT)):
            return listStr  
        return []  
    
    
    def addNetAddress(self, netaddress, addressType):  # 去除文件重复
        # 网络地址文件不存在时
        errmsg = ""
        contentList0 = StoreInfoParser.instance().getLocalNetworkList()
        contentList = []
        if contentList0:
            contentList = json.loads(contentList0)
        
        addNetName = netaddress["netName"]
        if (addressType == "dhcp"):
            card = netaddress["netCard"]
            addNetName += "-" + card
            
            
        for i in range(len(contentList)):
            if (contentList[i] == ""):
                continue
            subContent = contentList[i].split(":")
            netName = subContent[0]
            # 网络名称相同时
            if (netName == addNetName):
                if (addressType == "dhcp"):
                    errmsg = "dhcpnettoomany"
                    return False, errmsg
                errmsg = "netnametoomany"
                print errmsg
                return False, errmsg
            
        # 如果不重复，则将输入的有效信息写入该文件中，
        res = self.addNetAddressItem(netaddress, addressType)
        if (not res):
            return False, errmsg
        return True, errmsg
        
    def getNetAddressList(self):  # 得到本地网络列表，元素为字典
        netAddressList = []
        contentList0 = StoreInfoParser.instance().getLocalNetworkList()
        contentList = []
        if contentList0:
            contentList = json.loads(contentList0)
        for i in range(len(contentList)):
            subNetList = {}
            if (contentList[i] == ""):
                continue
            subList = contentList[i].split(":")
            subNetList["netName"] = subList[0]
            if (not QString(subNetList["netName"]).startsWith("dhcp")):
                subNetList["netIp"] = subList[1]
                subNetList["netMast"] = subList[2]
                subNetList["netGate"] = subList[3]
                subNetList["netDNS1"] = subList[4]
                subNetList["netDNS2"] = subList[5]
                subNetList["netCard"] = subList[6]
                subNetList["addressID"] = subList[7]
            else:
                subNetList["netCard"] = subList[1]
                subNetList["addressID"] = subList[2]
            netAddressList.append(subNetList)
        return netAddressList

    def delNetAddressItem(self, tempV):  # 从本地列表中删除一个当地网络
        contentCenterList0 = StoreInfoParser.instance().getCenterList()
        if(contentCenterList0 == None):
            pass
        else:
            contentCenterList = json.loads(contentCenterList0)
            for i in contentCenterList:
                if(str(contentCenterList[i]["networkName"]) == str(tempV)):
                    return -3
            
            
        contentLocalList0 = StoreInfoParser.instance().getLocalNetworkList()
        contentLocalList = []
        if contentLocalList0:
            contentLocalList = json.loads(contentLocalList0)
        
        text = self.getText(contentLocalList, tempV)
        netName = text.split(":")[0]
        if text == "":
            return "not in"
        contentLocalList.remove(text)
        StoreInfoParser.instance().setLocalNetworkList(json.dumps(contentLocalList, ensure_ascii=False))  
        
        currentNet = StoreInfoParser.instance().getCurrentLocalNetwork()
        if QString(currentNet).contains(tempV) or QString(currentNet).contains(netName):
            StoreInfoParser.instance().setCurrentLocalNetwork("")
        
    def getText(self, list, text):
        for i in range(len(list)):
            if QString(list[i]).contains(text):
                return list[i]
        return ""
    
    def getNetConf(self, command):
        fp = os.popen(command).read()
        result = fp.split("\n")[0]
        return result
    
    def getType(self):
        command = "cat /etc/sysconfig/network-scripts/ifcfg-eth0 | awk -F '=' '/BOOTPROTO/{print $2}'"
        type = self.getNetConf(command)
        return type
    def getIp(self):
        command = "cat /etc/sysconfig/network-scripts/ifcfg-eth0 | awk -F '=' '/IPADDR/{print $2}'"
        ip = self.getNetConf(command)
        return ip
    def getMask(self):
        command = "cat /etc/sysconfig/network-scripts/ifcfg-eth0 | awk -F '=' '/NETMASK/{print $2}'"
        mask = self.getNetConf(command)
        return mask
    def getGateWay(self):
        command = "cat /etc/sysconfig/network-scripts/ifcfg-eth0 | awk -F '=' '/GATEWAY/{print $2}'"
        gateway = self.getNetConf(command)
        return gateway
    def getDNSFirst(self):
        command = "cat /etc/sysconfig/network-scripts/ifcfg-eth0 | awk -F '=' '/DNS1/{print $2}'";
        dns_first = self.getNetConf(command)
        return dns_first
    def getDNSSecond(self):
        command = "cat /etc/sysconfig/network-scripts/ifcfg-eth0 | awk -F '=' '/DNS2/{print $2}'";
        dns_second = self.getNetConf(command)
        return dns_second
    def getMac(self):
        command = "cat /sys/class/net/eth0/address"
        macAddr = self.getNetConf(command)
        return macAddr.upper()
    
    def removeOldCfg(self, eth):  # 删除eth0的内容
        filePath = "/etc/sysconfig/network-scripts/ifcfg-" + eth
        if (not QFile.exists(filePath)):
            return False
        else:
            cmd0 = "sed -i '/BOOTPROTO/d' /etc/sysconfig/network-scripts/ifcfg-" + eth
            cmd1 = "sed -i '/IPADDR/d' /etc/sysconfig/network-scripts/ifcfg-" + eth
            cmd2 = "sed -i '/PREFIX/d' /etc/sysconfig/network-scripts/ifcfg-" + eth
            cmd3 = "sed -i '/GATEWAY/d' /etc/sysconfig/network-scripts/ifcfg-" + eth
            cmd4 = "sed -i '/NETMASK/d' /etc/sysconfig/network-scripts/ifcfg-" + eth
            cmd5 = "sed -i '/DNS1/d' /etc/sysconfig/network-scripts/ifcfg-" + eth
            cmd6 = "sed -i '/LAST_CONNECT/d' /etc/sysconfig/network-scripts/ifcfg-" + eth
            cmd7 = "sed -i '/PEER/d' /etc/sysconfig/network-scripts/ifcfg-" + eth
            cmd8 = "sed -i '/UUID/d' /etc/sysconfig/network-scripts/ifcfg-" + eth
#             cmd9 = "sed -i '/BRIDGE/d' /etc/sysconfig/network-scripts/ifcfg-" + eth
            cmd10 = "sed -i '/DNS2/d' /etc/sysconfig/network-scripts/ifcfg-" + eth
            cmd11 = "sed -i '/ONBOOT/d' /etc/sysconfig/network-scripts/ifcfg-" + eth
            cmd12 = "sed -i '/DEVICE/d' /etc/sysconfig/network-scripts/ifcfg-" + eth
            
            os.system(str(cmd0))
            os.system(str(cmd1))
            os.system(str(cmd2))
            os.system(str(cmd3))
            os.system(str(cmd4))
            os.system(str(cmd5))
            os.system(str(cmd6))
            os.system(str(cmd7))
            os.system(str(cmd8))
#             os.system(str(cmd9))
            os.system(str(cmd10))
            os.system(str(cmd11))
            os.system(str(cmd12))
#             os.system(str(cmd13))
            
            
            return True
        
    def setAuto(self, eth):  # 设置动态网路
        
        netcardList = "".join(commands.getstatusoutput("ls /etc/sysconfig/network-scripts/ifcfg-*")[1]).split("\n")
        print eth
        for i in netcardList:
            temp = "/etc/sysconfig/network-scripts/ifcfg-" + eth
            temp2 = "/etc/sysconfig/network-scripts/ifcfg-breth0"
            if(i != temp and i != temp2):
                cmd = "sed -i '/ONBOOT/d' " + i
                cmd2 = "echo 'ONBOOT=no' >> " + i
                os.system(str(cmd))
                os.system(str(cmd2))
            else:
                cmd = "sed -i '/ONBOOT/d' " + i
                cmd2 = "echo 'ONBOOT=yes' >> " + i
                os.system(str(cmd))
                os.system(str(cmd2))
        
        if eth != "breth0":
            result = self.removeOldCfg("breth0")
            if (result == False):
                return False
            cmd = "echo 'BOOTPROTO=dhcp' >> /etc/sysconfig/network-scripts/ifcfg-breth0"
            cmd2 = "echo 'ONBOOT=yes' >> /etc/sysconfig/network-scripts/ifcfg-breth0"
            cmd5 = "echo 'DEVICE=breth0' >> /etc/sysconfig/network-scripts/ifcfg-breth0"
            
            os.system(str(cmd2))
            os.system(str(cmd))
            os.system(str(cmd5))
        else:
            cmd = "sed -i '/ONBOOT/d' " + i
            cmd2 = "echo 'ONBOOT=yes' >> " + i
            os.system(str(cmd))
            os.system(str(cmd2))

        c = os.system("service network restart")
        if c == 0:
            return True
        else:
            return False
                

    def setStatic(self, eth, ip, mask, gateway, dns1, dns2):  # 设置静态网络
        netcardList = "".join(commands.getstatusoutput("ls /etc/sysconfig/network-scripts/ifcfg-*")[1]).split("\n")
        print "start ,,", netcardList
        for i in netcardList:
            temp = "/etc/sysconfig/network-scripts/ifcfg-" + eth
            temp2 = "/etc/sysconfig/network-scripts/ifcfg-breth0"
            temp3 = "/etc/sysconfig/network-scripts/ifcfg-lo"
            if(i != temp and i != temp2 and i != temp3):
                cmd = "sed -i '/ONBOOT/d' " + i
                cmd2 = "echo 'ONBOOT=no' >> " + i
                os.system(str(cmd))
                os.system(str(cmd2))
            else:
                cmd = "sed -i '/ONBOOT/d' " + i
                cmd2 = "echo 'ONBOOT=yes' >> " + i
                os.system(str(cmd))
                os.system(str(cmd2))
        
        if eth != "breth0":
            result = self.removeOldCfg("breth0")
            if(result):
                endeth = "breth0"
                settings7 = "echo " + "'" + "DEVICE=" + endeth + "'" + ">> /etc/sysconfig/network-scripts/ifcfg-" + endeth
                os.system(settings7)
                settings0 = "echo " + "'" + "BOOTPROTO=static" + "'" + ">> /etc/sysconfig/network-scripts/ifcfg-" + endeth
                settings1 = "echo " + "'" + "IPADDR=" + str(ip) + "'" + ">> /etc/sysconfig/network-scripts/ifcfg-" + endeth
                settings2 = "echo " + "'" + "NETMASK=" + str(mask) + "'" + ">> /etc/sysconfig/network-scripts/ifcfg-" + endeth
                settings3 = "echo " + "'" + "GATEWAY=" + str(gateway) + "'" + ">> /etc/sysconfig/network-scripts/ifcfg-" + endeth
                settings4 = "echo " + "'" + "DNS1=" + str(dns1) + "'" + ">> /etc/sysconfig/network-scripts/ifcfg-" + endeth
                settings5 = "echo " + "'" + "DNS2=" + str(dns2) + "'" + ">> /etc/sysconfig/network-scripts/ifcfg-" + endeth
                settings6 = "echo 'ONBOOT=yes' >> /etc/sysconfig/network-scripts/ifcfg-breth0"
                cmd_ifup = "ifup " + endeth

                a = os.system(str(settings0))
                b = os.system(str(settings1))
                c = os.system(str(settings2))
                d = os.system(str(settings3))
                e = os.system(str(settings4))
                f = os.system(str(settings5))
                g = os.system(str(settings6))
                h = os.system(str(cmd_ifup))
            else:
                return False

            k = os.system("service network restart")
            if a == 0 and b == 0 and c == 0 and d == 0 and e == 0 and f == 0 and g == 0 and k == 0:
                return True
            else:
                return False
        
    
    def writeToBreath(self, fileName, fileName2):
        readFile = QFile.exists(fileName)
        if(readFile != 0):
            readFile = QFile(fileName)
            if(readFile.open(QIODevice.ReadOnly) == 0):
                return QString("-2")  # 文件没有打开
            s = QTextStream(readFile)
            tempList1 = s.readAll()
            readFile.close()

            file_switch = QFile(fileName2)
            if(file_switch.open(QIODevice.WriteOnly) == 0):
                return QString("-2")
            s = QTextStream(file_switch)
            s << ""
            s << tempList1
            file_switch.close()
        else:
            return QString("-1")  # 目录没有打开
    
    def getCmdLine(self, command):
    
        fp = os.popen(command).read()

        result = fp.split("\n")
        return result
    def getWirelessList(self):
        cmd = "iwconfig"
        output = ""
        status = []
        status = commands.getstatusoutput(cmd)
        if status[0] == 0:
            output = status[1]
        else:
            output = ""
        outputList = output.split("\n")
        for i in range(len(outputList)):
            pass
        
    def isNetUsb(self):
        os.system("mv /etc/sysconfig/network-scripts/wlan0 /etc/sysconfig/network-scripts/ifcfg-wlan0")
        ok = os.system("service network restart")
        if ok == 0:
            return True
        else:
            os.system("mv /etc/sysconfig/network-scripts/ifcfg-wlan0 /etc/sysconfig/network-scripts/wlan0")
            return False
        

    def bridgetStaticNetstart(self, ip, mask, gateway, dns1, dns2):
        self.removeOldCfg("eth0")
        if (not QFile.exists("/etc/sysconfig/network-scripts/ifcfg-breth0")):
            ok = os.system("touch /etc/sysconfig/network-scripts/ifcfg-breth0")
            if ok != 0:
                return -1
        
            settings0 = "echo  'DEVICE=breth0' > /etc/sysconfig/network-scripts/ifcfg-breth0"
            settings1 = "echo  'TYPE=Bridge' >> /etc/sysconfig/network-scripts/ifcfg-breth0"            
            settings2 = "echo  'ONBOOT=yes' >> /etc/sysconfig/network-scripts/ifcfg-breth0"
            settings3 = "echo  'BOOTPROTO=static' >> /etc/sysconfig/network-scripts/ifcfg-breth0"  
            settings11 = "echo " + "'" + "IPADDR=" + str(ip) + "'" + ">> /etc/sysconfig/network-scripts/ifcfg-breth0"
            settings12 = "echo " + "'" + "NETMASK=" + str(mask) + "'" + ">> /etc/sysconfig/network-scripts/ifcfg-breth0"
            settings13 = "echo " + "'" + "GATEWAY=" + str(gateway) + "'" + ">> /etc/sysconfig/network-scripts/ifcfg-breth0"
            settings14 = "echo " + "'" + "DNS1=" + str(dns1) + "'" + ">> /etc/sysconfig/network-scripts/ifcfg-breth0"
            settings15 = "echo " + "'" + "DNS2=" + str(dns2) + "'" + ">> /etc/sysconfig/network-scripts/ifcfg-breth0"
                
            
            os.system(str(settings0))    
            os.system(str(settings1))
            os.system(str(settings2))
            os.system(str(settings3))
            
            os.system(str(settings11))
            os.system(str(settings12))
            os.system(str(settings13))
            os.system(str(settings14))    
            os.system(str(settings15))

            settings7 = "echo  'BOOTPROTO=none' >> /etc/sysconfig/network-scripts/ifcfg-eth0"        
            settings77 = "echo  'BRIDGE=breth0' >> /etc/sysconfig/network-scripts/ifcfg-eth0"        
            
            os.system(str(settings7))
            os.system(str(settings77))
            
        else:
            self.removeOldCfg("breth0")
            settings3 = "echo  'BOOTPROTO=static' >> /etc/sysconfig/network-scripts/ifcfg-breth0"  
            settings11 = "echo " + "'" + "IPADDR=" + str(ip) + "'" + ">> /etc/sysconfig/network-scripts/ifcfg-breth0"
            settings12 = "echo " + "'" + "NETMASK=" + str(mask) + "'" + ">> /etc/sysconfig/network-scripts/ifcfg-breth0"
            settings13 = "echo " + "'" + "GATEWAY=" + str(gateway) + "'" + ">> /etc/sysconfig/network-scripts/ifcfg-breth0"
            settings14 = "echo " + "'" + "DNS1=" + str(dns1) + "'" + ">> /etc/sysconfig/network-scripts/ifcfg-breth0"
            settings15 = "echo " + "'" + "DNS2=" + str(dns2) + "'" + ">> /etc/sysconfig/network-scripts/ifcfg-breth0"
            
            os.system(str(settings3))
            os.system(str(settings11))
            os.system(str(settings12))
            os.system(str(settings13))
            os.system(str(settings14))    
            os.system(str(settings15))
            
            
            settings8 = "echo  'BOOTPROTO=none' >> /etc/sysconfig/network-scripts/ifcfg-eth0"        
            settings88 = "echo  'BRIDGE=breth0' >> /etc/sysconfig/network-scripts/ifcfg-eth0"        
            os.system(str(settings8))
            os.system(str(settings88))
        
        
        os.system("ifconfig eth0 down")
        os.system("brctl addbr breth0")
        os.system("brctl addif breth0 eth0")
        
        netrestart = os.system("service network restart")
        if netrestart != 0:
            return -2
        
        return 0
    
    def bridgetNetstart(self, eth):
        self.removeOldCfg(eth)
        if (not QFile.exists("/etc/sysconfig/network-scripts/ifcfg-breth0")):
            os.system("touch /etc/sysconfig/network-scripts/ifcfg-breth0")
            
            settings0 = "echo  'DEVICE=breth0' > /etc/sysconfig/network-scripts/ifcfg-breth0"
            settings1 = "echo  'TYPE=Bridge' >> /etc/sysconfig/network-scripts/ifcfg-breth0"            
            settings2 = "echo  'ONBOOT=yes' >> /etc/sysconfig/network-scripts/ifcfg-breth0"
            settings3 = "echo  'BOOTPROTO=dhcp' >> /etc/sysconfig/network-scripts/ifcfg-breth0"  
            settings00 = "echo  'DELAY=0' >> /etc/sysconfig/network-scripts/ifcfg-breth0"   
            settings00 = "echo  'PEERNTP=yes' >> /etc/sysconfig/network-scripts/ifcfg-breth0"       
            
            os.system(str(settings0))    
            os.system(str(settings1))
            os.system(str(settings2))
            os.system(str(settings3))
            os.system(str(settings00))
            
            settings7 = "echo  'BOOTPROTO=none' >> /etc/sysconfig/network-scripts/ifcfg-eth0"  
            settings77 = "echo  'BRIDGE=breth0' >> /etc/sysconfig/network-scripts/ifcfg-eth0"        

            os.system(str(settings7))
            os.system(str(settings77))
        else:
            self.removeOldCfg("breth0")
            settings13 = "echo  'BOOTPROTO=dhcp' >> /etc/sysconfig/network-scripts/ifcfg-breth0"  
            settings8 = "echo  'BOOTPROTO=none' >> /etc/sysconfig/network-scripts/ifcfg-eth0" 
            settings88 = "echo  'BRIDGE=breth0' >> /etc/sysconfig/network-scripts/ifcfg-eth0"         

            os.system(str(settings8))
            os.system(str(settings13))
            os.system(str(settings88))
        
        
        os.system("ifconfig eth0 down")
        os.system("brctl addbr breth0")
        os.system("brctl addif breth0 eth0")
        
        netrestart = os.system("service network restart")
        
        if netrestart != 0:
            return -2
        return 0
    
    def bridgeStop(self):
        
        if (not QFile.exists("/etc/sysconfig/network-scripts/ifcfg-breth0")):
            return 0
        
        else:
            os.system("ifconfig breth0 down")
            os.system("brctl delbr breth0")
            os.system("mv /etc/sysconfig/network-scripts/ifcfg-breth0 /etc/sysconfig/network-scripts/breth0-bak")
            return 0
        
        