#coding:utf-8

import sunhpc
class Command(sunhpc.commands.set.host.command):
    """
    Sets the subnet for named interface on one of more hosts. 

    <arg type='string' name='host' repeat='1'>
    One or more named hosts.
    </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='subnet'>
    The subnet address of the interface. This is a named subnet and must be
    listable by the command 'sunhpc list network'.
    </arg>

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

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

    <example cmd='set host interface subnet compute-0-0 eth1 public'>
    Sets eth1 to be on the public subnet.
    </example>

    <example cmd='set host interface mac compute-0-0 iface=eth1 subnet=public'>
    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>
    """
    
    def run(self, params, args):

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

        if not len(args):
            self.abort('must supply host')
        if not iface:
            self.abort('must supply iface')
        if not subnet:
            self.abort('must supply subnet')

        for host in self.getHostnames(args):
            
            self.db.execute("""select net.name from
                networks net, nodes n where
                n.name='%s' and 
                net.node=n.id and 
                (net.device='%s' or net.mac='%s')""" % 
                (host, iface, iface))

            name, = self.db.fetchone()
            if not name: name = host

            # Updates the subnet id and the name.  The name
            # is updated even if it did not change (see above)
            self.db.execute("""update networks set 
                subnet=(select id from subnets s where s.name='%s'),
                name='%s' where
                node=(select id from nodes where nodes.name="%s") and
                (device='%s' or mac='%s')""" %
                (subnet, name, host, iface, iface))

RollName = "base"
