# coding=utf-8

""" create by pbc for network set
"""
import commands
import os,re
from threading import Thread
import time
from PyQt4.QtCore import QString, QSettings
from logger.logrecord import LogRecord

settings = QSettings("/mcos/network_set.ini", QSettings.IniFormat)
RET = None

# 获取所有网卡列表
def get_net_card_list():
    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 stop_all_netcard():
    _list_netcard = get_net_card_list()
    for i in range(len(_list_netcard)):
        _cmd_str = "ifconfig " + _list_netcard[i] + " down"
        os.system(_cmd_str)
    time.sleep(0.5)


# 开启某网卡设备
def start_netcard(card_name):
    _cmd_str = "ifconfig " + card_name + " up"
    ret = os.system(_cmd_str)
    time.sleep(0.5)
    return ret


# 重启网卡方法
def restart_network(net_card):
    _cmd_str = "ifdown " + net_card
    _cmd_str_2 = "ifup " + net_card
    r_1 = os.system(_cmd_str)
    r_2 = os.system(_cmd_str_2)
    if r_1 == 0 and r_2 == 0:
        return 0
    else:
        return -1

#获取当前使用的网卡名称
def get_currnet_netcard_name():
    ret = settings.value("currnet_netcard_name").toString()
    if ret == "":
        card_list = get_net_card_list()
        if len(card_list) > 0:
            return card_list[0]
    return ret

#设置当前使用的网卡名称
def set_currnet_netcard_name(name):
    settings.setValue("currnet_netcard_name", QString(name))

def save_local_interface_conf(file_value):
    fff = open('/mcos/interfaces', 'w')
    fff.write(file_value)
    fff.close()

# 设置动态网络
def set_dhcp_network(net_card):
    set_currnet_netcard_name(net_card)
    stop_all_netcard()
    start_netcard(net_card)

    value = "auto lo \n" \
            "iface lo inet loopback \n\n" \
            "auto " + net_card + " \n" + \
            "iface " + net_card + " inet dhcp"
    LogRecord.instance().logger.info(str(value))
    save_local_interface_conf(value)# add for heiping
    f = open('/etc/network/interfaces', 'w')
    f.write(str(value))
    f.close()
    conf_v = "dhcp:" + net_card
    settings.setValue("network_set", QString(conf_v))
    def do_restart_netcard_func():
        restart_network(net_card)
    sub_thread = Thread(target=do_restart_netcard_func)
    sub_thread.setDaemon(True)
    sub_thread.start()
    sub_thread.join(30.0)
    os.system("route add -net 192.168.102.0/24 gw 192.168.8.70")


    # f = open('/etc/network/interfaces', 'w')
    # f.write("")
    # f.close()


# 设置静态网络
def set_static_network(net_card, address, netmask, gateway):
    stop_all_netcard()
    start_netcard(net_card)

    value = "auto lo \n" \
            "iface lo inet loopback \n\n" \
            "auto " + net_card + " \n" + \
            "iface " + net_card + " inet static" + "\n" + \
            "address " + address + "\n" + \
            "netmask " + netmask + "\n" + \
            "gateway " + gateway
    LogRecord.instance().logger.info(str(value))
    save_local_interface_conf(value)# add for heiping
    f = open('/etc/network/interfaces', 'w')
    f.write(str(value))
    f.close()
    conf_v = "static:" + net_card + ":" + address + ":" + netmask + ":" + gateway
    settings.setValue("network_set", QString(conf_v))
    ret = restart_network(net_card)
    os.system("route add -net 192.168.102.0/24 gw 192.168.8.70")

    # f = open('/etc/network/interfaces', 'w')
    # f.write("")
    # f.close()


    return ret

#获取当前使用的网卡名称
def get_currnet_netcard_name():
    ret = settings.value("currnet_netcard_name").toString()
    return ret

#设置当前使用的网卡名称
def set_currnet_netcard_name(name):
    settings.setValue("currnet_netcard_name", QString(name))


#设置静态DNS
def set_static_dns(first_dns_address, second_dns_address=""):
    if first_dns_address != "" and second_dns_address != "":
        value = "nameserver " + first_dns_address + "\n" + \
                "nameserver " + second_dns_address
    else:
        value = "nameserver " + first_dns_address
    f = open('/etc/resolv.conf', 'w')
    f.write(value)
    f.close()
    settings.setValue("dns_set", "static")


def get_dns_dhcp_or_static():
     ret = settings.value("dns_set").toString()
     print "retrrr",ret
     if ret == "":
         return "dhcp"
     return ret


def set_dhcp_dns():
    f = open('/etc/resolvconf/resolv.conf.d/base', 'w')
    f.write("")
    f.close()

    f = open('/etc/resolv.conf', 'w')
    f.write("")
    f.close()
    _cmd_str = "resolvconf -u"
    os.system(_cmd_str)
    settings.setValue("dns_set", "dhcp")


def get_dns_list():
    dns_list = []
    f = open('/etc/resolv.conf', 'r')
    value = f.read()
    value_list = value.split("\n")
    for i in range(len(value_list)):
        if value_list[i] != "":
            tmp_list = value_list[i].split(" ")
            if len(tmp_list) == 2:
                dns_list.append(str(QString(tmp_list[1]).trimmed()))
    return dns_list

def  get_local_net_information():
    value_list = settings.value("network_set").toString()
    if value_list == "":
        return ""
    else:
        return value_list.split(":")

def isIP(ip):
    """
    验证IP是否是有效IP
    :param ip:
    :return:
    """
    ipReg=re.compile('^((\\d|[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5])\\.){3}(\\d|[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-4])$')
    if not re.match(ipReg,ip):
        return False
    return True

def getNetMaskFromLen(length):
    if not isinstance(length,int):
        LogRecord.instance().logger.warn("掩码长度格式错误！")
        return ''
    if (length > 31 or
        length < 1):
        LogRecord.instance().logger.warn("掩码长度不在合适的范围内！")
        return ''
    sectionNumber = length//8
    tailLen = length%8
    netmask = ''
    if sectionNumber == 0:
        netmask += str((2**tailLen-1)*(2**(8-tailLen)))
        netmask += '.0.0.0'
    elif sectionNumber == 1:
        netmask += '255.'
        netmask += str((2**tailLen-1)*(2**(8-tailLen)))
        netmask += '.0.0'
    elif sectionNumber == 2:
        netmask += '255.255.'
        netmask += str((2**tailLen-1)*(2**(8-tailLen)))
        netmask += '.0'
    elif sectionNumber == 3:
        netmask += '255.255.255.'
        netmask += str((2**tailLen-1)*(2**(8-tailLen)))
    else:
        netmask = ''
    return netmask

def get_auto_ip_list():
    ip_list = []
    try:
        proc = os.popen('ip route show')
        resStr = proc.read()
        proc.close()
        LogRecord.instance().logger.debug(resStr)
        if not isinstance(resStr,str):
            LogRecord.instance().logger.warn("运行获取ip设置命令“ip route show”失败！")
            return []
        if len(resStr) < 1:
            LogRecord.instance().logger.warn("运行获取ip设置命令“ip route show”失败！")
            return []
        lines = resStr.splitlines()
        gateway = ''
        netCard = ''
        for line in lines:
            if line.find('default via') >= 0:
                _,tmp =line.strip().split('default via',1)
                gateway,netCard = tmp.split('dev',1)
                gateway = gateway.strip()
                netCard = netCard.strip().split()[0]
                netCard = netCard.strip()
                if not isIP(gateway):
                    LogRecord.instance().logger.warn('获取到了错误的网关信息！网关:'+gateway)
                    return []
                break
        if (gateway == ''):
            LogRecord.instance().logger.warn('没有获取到网关配置信息！')
            return []
        if (netCard == ''):
            LogRecord.instance().logger.warn('没有获取到默认网卡！')
            return []
        netmask = ''
        ip = ''
        for line in lines:
            if (line.find(netCard) >= 0 and
                line.find('src') >= 0):
                netmask,tail = line.split('dev',1)
                _,maskLen = netmask.strip().split('/',1)
                try:
                    maskLength = int(maskLen)
                    netmask = getNetMaskFromLen(maskLength)
                    if not isIP(netmask):
                        LogRecord.instance().logger.warn("得到了错误的子网掩码！")
                        return []
                except Exception,err:
                    LogRecord.instance().logger.exception("子网掩码长度转换错误！")
                    return []
                _,ip = tail.split('src',1)
                ip = ip.strip().split()[0]
                if not isIP(ip):
                    LogRecord.instance().logger.warn("获取到的动态ip格式错误！")
                    return []
                break
        if (ip == '' or
            netmask == ''):
            LogRecord.instance().logger.warn("获取到的动态ip失败！")
            return []
        ip_list.append(ip)
        ip_list.append(netmask)
        ip_list.append(gateway)
        return ip_list
    except Exception,err:
        LogRecord.instance().logger.exception("运行获取ip设置命令“ip route show”异常！")
        return []


# print "this is get ",get_currnet_netcard_name()
# print "this is set",set_currnet_netcard_name("eth0")
# retu = get_local_net_information()
# print get_dns_list()
# set_dhcp_dns()
# set_static_dns("114.114.114.114","8.8.8.8")
# print start_netcard("eth0")
# stop_all_netcard()
# print get_net_card_list()
# print set_dhcp_network("eth0")
# print set_static_network("eth0", "192.168.8.157", "255.255.255.0", "192.168.8.254")

if __name__ == "__main__":
    import sys
    from PyQt4 import QtGui
    app = QtGui.QApplication(sys.argv)
    print get_auto_ip_list()
    sys.exit(app.exec_())





