#coding:utf-8

import sunhpc
class Command(sunhpc.commands.set.host.command):
    """
    Sets the mac address for named interface on 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='mac'>
    The mac address of the interface. Usually of the form dd:dd:dd:dd:dd:dd
    where d is a hex digit. This format is not enforced. Use mac=NULL to
    clear the mac address.
    </arg>

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

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

    <example cmd='set host interface mac compute-0-0 eth1 00:0e:0c:a7:5d:ff'>
    Sets the MAC Address for the eth1 device on host compute-0-0.
    </example>

    <example cmd='set host interface mac compute-0-0 iface=eth1 mac=00:0e:0c:a7:5d:ff'>
    Same as above.
    </example>
    
    <example cmd='set host interface mac compute-0-0 iface=eth1 mac=NULL'>
    clears the mac address from the database
    </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>
    """
    
    def run(self, params, args):

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

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

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

RollName = "base"
