#coding:utf-8

import sunhpc
import socket
class Command(sunhpc.commands.set.host.command):
    """
    Sets the IP address for the named interface for one host.

    <arg type='string' name='host'>
    Host name.
    </arg>
    
    <arg type='string' name='iface'>
    Interface that should be updated. This may be a logical interface or 
    the mac address of the interface.
    </arg>
    
    <arg type='string' name='ip'>
    The IP address of the interface. Usually of the form nnn.nnn.nnn.nnn
    where n is a decimal digit. This format is not enforced. Use IP=NULL
    to clear.
    </arg>

    <param type='string' name='iface'>
    Can be used in place of the iface argument.
    </param>

    <param type='string' name='ip'>
    Can be used in place of the ip argument.
    </param>
    

    <example cmd='set host interface ip compute-0-0 eth1 192.168.0.10'>
    Sets the IP Address for the eth1 device on host compute-0-0.
    </example>

    <example cmd='set host interface ip compute-0-0 iface=eth1 ip=192.168.0.10'>
    Same as above.
    </example>
    
    <related>set host interface iface</related>
    <related>set host interface ip</related>
    <related>set host interface module</related>
    <related>add host</related>
    """
    
    def run(self, params, args):

        (args, iface, ip) = self.fillPositionalArgs(('iface', 'ip'))

        hosts = self.getHostnames(args)
        
        if len(hosts) != 1:
            self.abort('must supply one host')
        if not iface:
            self.abort('must supply iface')
        if not ip:
            self.abort('must supply ip')

        ip = ip.upper() # null -> NULL
        if ip != 'NULL':
            #let's check if this is a valid IPv4 address
            #for IPv6 use socket.AF_INET6
            try:
                socket.inet_pton(socket.AF_INET, ip)
            except:
                self.abort("The ip address %s is invalid" % ip )
        
        for host in hosts:
            self.db.execute("""update networks set ip=NULLIF('%s','NULL') 
                where node=(select id from nodes where nodes.name="%s") and
                (networks.device='%s' or networks.mac='%s')""" %
                (ip, host, iface, iface))

RollName = "base"












