#coding:utf-8

import os
import sys
import stat
import time
import string
import sunhpc
class Command(sunhpc.commands.add.host.command):
    """
    Adds an interface to a host and sets the associated values 

    <arg type='string' name='host'>
    Host name of machine
    </arg>
    
    <arg type='string' name='iface'>
    The interface name on the host (e.g., 'eth0', 'eth1')
    </arg>
    
    <param type='string' name='iface'>
    Can be used in place of the iface argument.
    </param>

    <param type='string' name='ip'>
    The IP address to assign to the interface (e.g., '192.168.1.254')
    </param>

    <param type='string' name='subnet'>
    The name of the subnet to assign to the interface (e.g., 'private')
    </param>
    
    <param type='string' name='name'>
    The name to assign to the interface
    </param>
    
    <param type='string' name='mac'>
    The MAC address of the interface (e.g., '00:11:22:33:44:55')
    </param>
    
    <example cmd='add host interface compute-0-0 eth1 ip=192.168.1.2 subnet=private name=fast-0-0'>
    </example>
    
    <example cmd='add host interface compute-0-0 iface=eth1 ip=192.168.1.2 subnet=private name=fast-0-0'>
    same as above
    </example>

    <related>set host interface iface</related>
    <related>set host interface ip</related>
    <related>set host interface mac</related>
    <related>set host interface name</related>
    <related>set host interface subnet</related>
    """

    def run(self, params, args):

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

        hosts = self.getHostnames(args)

        if not iface:
            self.abort('missing iface')

        if len(hosts) != 1: 
            self.abort('must supply one host')
        host = hosts[0]

        #
        # determine if this is an interface name or a MAC address
        #

        isMac = 0
        m = iface.split(':')
        if len(m) >= 6:
            isMac = 1

        rows = self.db.search("""select * from networks,nodes where 
            nodes.name='%s' and
            (networks.device='%s' or networks.mac='%s') and
            networks.node=nodes.id""" % (host, iface, iface))
        if rows:
            self.abort('interface "%s" exists' % iface)

        if isMac:
            self.db.execute("""insert into networks(node,mac)
                values ((select id from nodes where name='%s'),
                '%s')""" % (host, iface)) 
        else:
            self.db.execute("""insert into networks(node,device)
                values ((select id from nodes where name='%s'),
                '%s')""" % (host, iface)) 

        for key in ['ip', 'mac', 'name', 'subnet']:
            if key in params:
                self.command('set.host.interface.%s' % key,
                    (host, iface, params[key]))
RollName = "base"












