import subprocess

class kvmIPs:
    """ a helper class to deal with IPs and Hostnames
    """

    servers=""
    """ List of servers defined in this install
    """
    privateNetwork=""
    
    def __init__(self,servers, privateNetwork):
        self.servers=servers
        self.privateNetwork=privateNetwork

    def ipWithoutDots(self,ipv4addr,sep):
        # return this ipv4 addr with _ rather than .
        ip1, ip2, ip3, ip4 = ipv4addr.split('.')
        return ip1+sep+ip2+sep+ip3+sep+ip4

    def ipForServer(self,index):
        # what IP should we try to contact this server via?
        #  its based on the the first x.y.z from config_data[env][privateNetwork]
        #       and the w from index+1
        ip1, ip2, ip3, ip4 = self.privateNetwork.split('.')
        ip=ip1+"."+ip2+"."+ip3+"."+str(index+1)
        return ip


    def hostnameForServer(self,index):
        # create a hostname for this server
        # in this format
        #
        #       hostname is nas-x-y-z-w
        #

        return "nas-"+self.ipWithoutDots(self.ipForServer(index),"-")

    def prepTargetHostEntries(self,server):
        # extend this servers /etc/hosts file with all known servers in the config.json
        # format mapping is as follows
        #
        #       /etc/hosts entry is     x.y.z.w virt-x-y-z-w
        #
        # where ip for a hostnode is based on how manuy hostnodes there are

        index=0
        for srv in self.servers:
            index += 1
            hostname=self.hostnameForServer(index)
            # does this host already exist in the hosts file?
            retval = subprocess.call(['ssh',server["accessIP"],
                    'grep '+hostname+' /etc/hosts >/dev/null 2>&1'])
            if retval==1:
                # then the entry isn't there and we'll add it.
                retval = subprocess.call(['ssh',server["accessIP"],
                    'echo '+self.ipForServer(index)+" "+hostname+' >> /etc/hosts'])
                if retval != 0:
                    self.setError("Failed to append server "+svr["accessIP"]+" to "+server["accessIP"]+" servers hosts file. Error:"+str(retval))
                    return 1

        return 0
