import subprocess
import os
from baseCheck import baseCheck

class duplicateIPs(baseCheck):

    customerIPs = {}
    privateIPs = {}
    kvmIPs = {}

    def getHumanName(self):
        return "Check for duplicate static IPs"

    def runCheck(self,config, debug):
        # confirm static customer (and private) IPs are not duplicated!
        returnCode=0
        
        for server in config["environment"]["servers"]:

            ip = server["accessIP"]
            if ip in self.kvmIPs:
                # this is a problem.
                self.addFailure("KVM IP address "+ip+" is a duplicate of another defined KVM server. Please assign unique IP addresses for each KVM server.")
            else:
                self.kvmIPs[ip]=server

            for vm in server['vms']:
                ip = vm['customerIP']
                if ip != "" and ip != 'dhcp':
                    # then its a static.  make sure we've not heard it before!
                    if ip in self.customerIPs:
                        # this is a problem.                        
                        self.addFailure("IP address "+ip+" assigned as customerIP to vm "+vm["name"]+" on host "+server["accessIP"]+" is a duplicate of the IP assigned to vm "+self.customerIPs[ip]['name']+". Please remove the duplicate.")
                    else:
                        self.customerIPs[ip]=vm

                ip = vm['privateIP']
                if ip != "" and ip != 'dhcp':
                    # then its a static.  make sure we've not heard it before!
                    if ip in self.privateIPs:
                        # this is a problem.
                        self.addFailure("IP address "+ip+" assigned as private IP to vm "+vm["name"]+" on host "+server["accessIP"]+" is a duplicate of the IP assigned to vm "+self.privateIPs[ip]['name']+". Please remove the duplicate.")
                    else:
                        self.privateIPs[ip]=vm
                
        # finally - make sure the VIP doesn't collide
        vip=config["environment"]["vip"]
        if vip in self.customerIPs:
            # we have a problem.
            self.addFailure("VIP address "+vip+" assigned is duplicated with another VM. Please remove the duplicate or change the VIP.")

        return returnCode
