#coding:utf-8

import sunhpc
class Command(sunhpc.commands.set.host.command):
    """
    Sets the logical name of a network interface on a particular 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='name'>
    Name of this interface (e.g. newname). This is only the
    name associated with a certain interface. FQDNs are disallowed.
    To set the domain or zone for an interface, use the
    "sunhpc add network" command, and then associate the interface
    with the network
    </arg>

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

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

    <example cmd='set host interface name compute-0-0 eth1 cluster-0-0'>
    Sets the name for the eth1 device on host compute-0-0 to
    cluster-0-0.zonename. The zone is decided by the subnet that the
    interface is attached to.
    </example>

    <example cmd='set host interface name compute-0-0 iface=eth1 name=c0-0'>
    Same as above.
    </example>
    
    <!-- cross refs do not exist yet
    <related>set host interface iface</related>
    <related>set host interface ip</related>
    <related>set host interface module</related>
    -->
    <related>add host</related>
    <related>add network</related>
    """
    
    def run(self, params, args):

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

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

        # One host only
        host = hosts[0]

        if not iface:
            self.abort('must supply iface')
        if not name:
            self.abort('must supply name')

        if len(name.split('.')) > 1:
            self.abort('cannot be fqdn\n' +\
            'Please use subnets table to set domain name')

        if name.upper() == "NULL":
            name = host

        self.db.execute("""update networks set networks.name='%s' 
            where 
            node=(select id from nodes where nodes.name="%s") and
            (networks.device='%s' or networks.mac='%s')""" %
            (name, host, iface, iface))

RollName = "base"
