#coding=utf-8
import os
import codecs
import ConfigParser

from logger.logrecord import LogRecord

class modifyNetWork():
    """
    修改本机ip配置
    """
    infos={}#用来暂时存储配置文件内容
    infos["main"]={}
    infos["main"]["plugins"]='ifupdown,keyfile,ofono'
    infos["main"]["dns"]='dnsmasq'
    infos["ifupdown"]={}#配置类型
    infos["ifupdown"]["managed"]='false'#具体配置项
    # infos["ifupdown"]["center_port"]='8080'#具体配置项
    parser = ConfigParser.ConfigParser()
    @staticmethod
    def setStaticIP(netCard,ip,subnetMask,gateWay,DNS1,DNS2):
        """
        设置静态ip
        :param netCard: 网卡名
        :param ip: ip地址
        :param subnetMask: 子网掩码
        :param gateWay: 网关
        :param DNS1: 首选dns
        :param DNS2: 备用dns
        :return:
        """
        if DNS1 == '':
            if (DNS2 != '') and (DNS2 != None):
                DNS1 = DNS2
                DNS2 = ''
        if os.path.exists('/etc/network/interfaces'):
            try:
                f=open('/etc/network/interfaces','w')
                f.truncate()
                # f.write('auto lo\n')
                # f.write('iface lo inet loopback\n\n')
                f.write('auto %s\n'%netCard)
                f.write('iface %s inet static\n'%netCard)
                f.write('address %s\n'%ip)
                f.write('netmask %s\n'%subnetMask)
                f.write('gateway %s\n'%gateWay)
                f.write('dns-nameservers %s\n'%DNS1)
            except Exception , err:
                LogRecord.instance().logger.exception('对文件/etc/network/interfaces的读写操作异常！')
            finally:
                f.close()
        else:
            LogRecord.instance().logger.debug('文件：/etc/network/interfaces 不存在!')
            try:
                f=open('/etc/network/interfaces','w')
                f.truncate()
                f.write('auto %s\n'%netCard)
                f.write('iface %s inet static\n'%netCard)
                f.write('address %s\n'%ip)
                f.write('netmask %s\n'%subnetMask)
                f.write('gateway %s\n'%gateWay)
                if DNS1 != '':
                    f.write('dns-nameservers %s\n'%DNS1)
                if DNS2 != '':
                    f.write('dns-nameservers %s\n'%DNS2)
            except Exception , err:
                LogRecord.instance().logger.exception('对文件/etc/network/interfaces的读写操作异常！')
            finally:
                f.close()
        if os.path.exists('/run/resolvconf/resolv.conf'):
            try:
                f=open('/run/resolvconf/resolv.conf','w')
                f.truncate()
                f.write('nameserver %s\n'%DNS1)
                f.write('nameserver %s\n'%DNS2)
            except Exception , err:
                LogRecord.instance().logger.exception('对文件/run/resolvconf/resolv.conf的读写操作异常！')
            finally:
                f.close()
        else:
            LogRecord.instance().logger.debug('文件：/run/resolvconf/resolv.conf 不存在!')
            try:
                f=open('/run/resolvconf/resolv.conf','w')
                f.truncate()
                f.write('nameserver %s\n'%DNS1)
                f.write('nameserver %s\n'%DNS2)
            except Exception , err:
                LogRecord.instance().logger.exception('对文件/run/resolvconf/resolv.conf的读写操作异常！')
            finally:
                f.close()
        if os.path.exists('/etc/resolvconf/resolv.conf.d/base'):
            try:
                f=open('/etc/resolvconf/resolv.conf.d/base','w')
                f.truncate()
                f.write('nameserver %s\n'%DNS1)
                f.write('nameserver %s\n'%DNS2)
            except Exception , err:
                LogRecord.instance().logger.exception('对文件/etc/resolvconf/resolv.conf.d/base的读写操作异常！')
            finally:
                f.close()
        else:
            LogRecord.instance().logger.debug('文件：/etc/resolvconf/resolv.conf.d/base 不存在!')
            try:
                f=open('/etc/resolvconf/resolv.conf.d/base','w')
                f.truncate()
                f.write('nameserver %s\n'%DNS1)
                f.write('nameserver %s\n'%DNS2)
            except Exception , err:
                LogRecord.instance().logger.exception('对文件/etc/resolvconf/resolv.conf.d/base的读写操作异常！')
            finally:
                f.close()
        try:
            modifyNetWork.read('/etc/NetworkManager/NetworkManager.conf')
            modifyNetWork.infos["ifupdown"]["managed"]='true'
            modifyNetWork.save('/etc/NetworkManager/NetworkManager.conf')
        except Exception,err:
            LogRecord.instance().logger.exception("读写/etc/NetworkManager/NetworkManager.conf失败！")
        os.system('/etc/init.d/networking restart')
        os.system('sudo service network-manager restart')
    @staticmethod
    def read(fileName):
        """
        读取配置文件内容
        :param fileName: 配置文件名
        :return:读取配置文件是否成功
        """
        try:
            fp = codecs.open(fileName, "r", "utf-8")
            modifyNetWork.parser.readfp(fp)
        except Exception, err:
            return False
        for section in modifyNetWork.infos.keys():
            for key in modifyNetWork.infos[section].keys():
                if modifyNetWork.parser.has_option(section, key):
                    tmp = modifyNetWork.parser.get(section, key)
                    #添加判断该项是否合法与有效
                    modifyNetWork.infos[section][key] = tmp
                else:
                    LogRecord.instance().logger.warn('找不到配置项： %s,%s'%(section,key))
        # print Config.infos
        return True
    @staticmethod
    def save(fileName):
        """
        保存修改的配置
        :param fileName: 配置文件名
        :return:是否成功
        """
        for section in modifyNetWork.infos.keys():
            for key in modifyNetWork.infos[section].keys():
                modifyNetWork.parser.set(section,key,modifyNetWork.infos[section][key])
        try:
            fp = codecs.open(fileName, "w", "utf-8")
            modifyNetWork.parser.write(fp)
        except Exception, err:
            return False
        return True
    @staticmethod
    def setAutoIP(DNS1='',DNS2=''):
        if DNS1 == '':
            if (DNS2 != '') and (DNS2 != None):
                DNS1 = DNS2
                DNS2 = ''
        if os.path.exists('/etc/network/interfaces'):
            try:
                f=open('/etc/network/interfaces','w')
                f.truncate()
                f.write('auto lo\n')
                f.write('iface lo inet loopback\n\n')
                if DNS1 != '':
                    if DNS2 != '':
                        f.write('dns-nameservers %s %s\n'%(DNS1,DNS2))
                    else:
                        f.write('dns-nameservers %s\n'%DNS1)
            except Exception , err:
                LogRecord.instance().logger.exception('对文件/etc/network/interfaces的读写操作异常！')
            finally:
                f.close()
        else:
            LogRecord.instance().logger.debug('文件：/etc/network/interfaces 不存在!')
            try:
                f=open('/etc/network/interfaces','w')
                f.truncate()
                f.write('auto lo\n')
                f.write('iface lo inet loopback\n\n')
                if DNS1 != '':
                    if DNS2 != '':
                        f.write('dns-nameservers %s %s\n'%(DNS1,DNS2))
                    else:
                        f.write('dns-nameservers %s\n'%DNS1)
            except Exception , err:
                LogRecord.instance().logger.exception('对文件/etc/network/interfaces的读写操作异常！')
            finally:
                f.close()
        if os.path.exists('/etc/dhcp/dhclient.conf'):
            try:
                f=open('/etc/dhcp/dhclient.conf','r+')
                content=f.read()
                f.seek(0)
                f.truncate()
                if content.find('prepend domain-name-servers ') >= 0:
                    flag=False
                    conLines=content.splitlines(True)
                    for line in conLines:
                        index=line.find('prepend domain-name-servers ')
                        if index >= 0:
                            commentIndex=line.find('#')
                            if (commentIndex >= 0) and (commentIndex < index):
                                f.write(line)
                            else:
                                flag=True
                                line = 'prepend domain-name-servers %s,%s;\n'%(DNS1,DNS2)
                                f.write(line)
                        else:
                            f.write(line)
                    if not flag:
                        line = 'prepend domain-name-servers %s,%s;\n'%(DNS1,DNS2)
                        f.write(line)
                else:
                    f.write(content)
                    f.write('prepend domain-name-servers %s,%s;\n'%(DNS1,DNS2))

            except Exception,err:
                LogRecord.instance().logger.exception('对文件/etc/dhcp/dhclient.conf的读写操作异常！')
            finally:
                f.close()
        if os.path.exists('/run/resolvconf/resolv.conf'):
            try:
                f=open('/run/resolvconf/resolv.conf','w')
                f.truncate()
                f.write('nameserver %s\n'%DNS1)
                f.write('nameserver %s\n'%DNS2)
            except Exception , err:
                LogRecord.instance().logger.exception('对文件/run/resolvconf/resolv.conf的读写操作异常！')
            finally:
                f.close()
        else:
            LogRecord.instance().logger.debug('文件：/run/resolvconf/resolv.conf 不存在!')
            try:
                f=open('/run/resolvconf/resolv.conf','w')
                f.truncate()
                f.write('nameserver %s\n'%DNS1)
                f.write('nameserver %s\n'%DNS2)
            except Exception , err:
                LogRecord.instance().logger.exception('对文件/run/resolvconf/resolv.conf的读写操作异常！')
            finally:
                f.close()
        if os.path.exists('/etc/resolvconf/resolv.conf.d/base'):
            try:
                f=open('/etc/resolvconf/resolv.conf.d/base','w')
                f.truncate()
                f.write('nameserver %s\n'%DNS1)
                f.write('nameserver %s\n'%DNS2)
            except Exception , err:
                LogRecord.instance().logger.exception('对文件/etc/resolvconf/resolv.conf.d/base的读写操作异常！')
            finally:
                f.close()
        else:
            LogRecord.instance().logger.debug('文件：/etc/resolvconf/resolv.conf.d/base 不存在!')
            try:
                f=open('/etc/resolvconf/resolv.conf.d/base','w')
                f.truncate()
                f.write('nameserver %s\n'%DNS1)
                f.write('nameserver %s\n'%DNS2)
            except Exception , err:
                LogRecord.instance().logger.exception('对文件/etc/resolvconf/resolv.conf.d/base的读写操作异常！')
            finally:
                f.close()
        try:
            modifyNetWork.read('/etc/NetworkManager/NetworkManager.conf')
            modifyNetWork.infos["ifupdown"]["managed"]='true'
            modifyNetWork.save('/etc/NetworkManager/NetworkManager.conf')
        except Exception,err:
            LogRecord.instance().logger.exception("读写/etc/NetworkManager/NetworkManager.conf失败！")
        os.system('/etc/init.d/networking restart')
        os.system('sudo service network-manager restart')
    @staticmethod
    def setAutoDNS(netCard):
        if os.path.exists('/etc/network/interfaces'):
            try:
                f=open('/etc/network/interfaces','w')
                f.truncate()
                f.write('auto lo\n')
                f.write('iface lo inet loopback\n\n')
            except Exception , err:
                LogRecord.instance().logger.exception('对文件/etc/network/interfaces的读写操作异常！')
            finally:
                f.close()
        else:
            LogRecord.instance().logger.debug('文件：/etc/network/interfaces 不存在!')
            try:
                f=open('/etc/network/interfaces','w')
                f.truncate()
                f.write('auto lo\n')
                f.write('iface lo inet loopback\n\n')
            except Exception , err:
                LogRecord.instance().logger.exception('对文件/etc/network/interfaces的读写操作异常！')
            finally:
                f.close()
        if os.path.exists('/etc/dhcp/dhclient.conf'):
            try:
                f=open('/etc/dhcp/dhclient.conf','r+')
                content=f.read()
                f.seek(0)
                f.truncate()
                if content.find('prepend domain-name-servers ') >= 0:
                    conLines=content.splitlines(True)
                    for line in conLines:
                        index=line.find('prepend domain-name-servers ')
                        if index >= 0:
                            commentIndex=line.find('#')
                            if (commentIndex >= 0) and (commentIndex < index):
                                f.write(line)
                        else:
                            f.write(line)
                else:
                    f.write(content)
            except Exception,err:
                LogRecord.instance().logger.exception('对文件/etc/dhcp/dhclient.conf的读写操作异常！')
            finally:
                f.close()
        if os.path.exists('/run/resolvconf/resolv.conf'):
            try:
                f=open('/run/resolvconf/resolv.conf','w')
                f.truncate()
                f.write('')
            except Exception , err:
                LogRecord.instance().logger.exception('对文件/run/resolvconf/resolv.conf的读写操作异常！')
            finally:
                f.close()
        else:
            LogRecord.instance().logger.debug('文件：/run/resolvconf/resolv.conf 不存在!')
            try:
                f=open('/run/resolvconf/resolv.conf','w')
                f.truncate()
                f.write('')
            except Exception , err:
                LogRecord.instance().logger.exception('对文件/run/resolvconf/resolv.conf的读写操作异常！')
            finally:
                f.close()
        if os.path.exists('/etc/resolvconf/resolv.conf.d/base'):
            try:
                f=open('/etc/resolvconf/resolv.conf.d/base','w')
                f.truncate()
                f.write('')
            except Exception , err:
                LogRecord.instance().logger.exception('对文件/etc/resolvconf/resolv.conf.d/base的读写操作异常！')
            finally:
                f.close()
        else:
            LogRecord.instance().logger.debug('文件：/etc/resolvconf/resolv.conf.d/base 不存在!')
            try:
                f=open('/etc/resolvconf/resolv.conf.d/base','w')
                f.truncate()
                f.write('')
            except Exception , err:
                LogRecord.instance().logger.exception('对文件/etc/resolvconf/resolv.conf.d/base的读写操作异常！')
            finally:
                f.close()
        try:
            modifyNetWork.read('/etc/NetworkManager/NetworkManager.conf')
            modifyNetWork.infos["ifupdown"]["managed"]='true'
            modifyNetWork.save('/etc/NetworkManager/NetworkManager.conf')
        except Exception,err:
            LogRecord.instance().logger.exception("读写/etc/NetworkManager/NetworkManager.conf失败！")
        os.system('/etc/init.d/networking restart')
        os.system('sudo service network-manager restart')


