#!/usr/bin/env python
#coding=utf-8

from ip_port_check import ip_check

import os
class DomainMap(object):
    def __init__(self):
        self.__hostFilePath = "/etc/hosts"    

    #添加域名映射
    # 成功 [True，""]
    # 失败 [False，"info"]
    def addDomainMap(self,ip,domain):

        if not ip_check(ip):  # 检查 ip格式 是否正确
            return False,"域名映射,ip格式错误"

        if not os.path.exists(self.__hostFilePath):
            return False,"%s 不存在" % self.__hostFilePath
     
        res = self.__findDomainMap(ip,domain)

        if res[0] == False:
            fd = None
            try:
                fd = open(self.__hostFilePath,"a+")     
                domainmap = "\n%s  %s\n" % (ip,domain)
                fd.write(domainmap)
            except Exception as e:
                return False,""
            finally:
                if fd != None:
                    fd.close()

        return True,"" 

    def __findDomainMap(self,ip,domain):
        ''' 查找 host文件 是否以存在 域名映射 '''
        fd = None
        try:
            fd = open(self.__hostFilePath,"r")     

            for eachline in fd:  # 文件迭代，等价与，for eachline in fd.readlines():
                dmap =  eachline.split(" ",1)   # 空格隔开
                if 1 == len(dmap):
                    dmap =  eachline.split("\t",1) # Tab 隔开

                import re 
                for i in range(len(dmap)):
                    dmap[i] = re.sub("\t","",dmap[i])   # 清除 Tab
                    dmap[i] = re.sub(" ","",dmap[i])    # 清除 空格
                    dmap[i] = re.sub("\n","",dmap[i])   # 清除 换行

                if len(dmap) == 2:
                    if domain == dmap[1]: # 域名相同
                        # fd.close()
                        return True,""
                # print dmap
            # fd.close()
            return False, ""

        except Exception as e:
            return False,""

        finally:
            if fd != None:
                fd.close()

if __name__ == "__main__":
    domain = DomainMap()
    print domain.addDomainMap("192.0.0.1","server888.com")
    # domain.addDomainMap("192.0.0.2","server28.com")
    # domain.addDomainMap("192.0.0.3","server29.com")


# data = open(filename, 'rt').readlines()
# with open(filename, 'wt') as handle:
#     handle.writelines(data[:tobedeleted])
#     handle.writelines(data[tobedeleted+1:])

