#coding:utf-8

import sys
import socket
import sunhpc
class Command(sunhpc.commands.HostArgumentProcessor,
        sunhpc.commands.report.command):
    """
    Report the set of attributes for hosts.

    <arg optional='1' type='string' name='host'>
    Host name of machine
    </arg>

    <param optional='1' type='string' name='attr'>
    Output just the value of a particular attribute 
    </param>
    
    <param optional='1' type='bool' name='pydict'>
    Output as a python-formatted dictionary. Defaults to false.
    Only valid if attr parameter is not specified.
    </param>
    
    <example cmd='report host attr compute-0-0'>
    Report the attributes for compute-0-0.
    </example>

    <example cmd='report host attr compute-0-0 pydict=true'>
    Report the attributes for compute-0-0 as a python dictionary suitable
    for input to sunhpc report script.
    </example>

    <example cmd='report host attr compute-0-0 attr=Kickstart_Lang'>
    Output value of the attribute called Kickstart_Lang for node
    compute-0-0.
    </example>

    <related>report script</related>
    """

    def run(self, params, args):

        (attr, pydict) = self.fillParams([('attr', ),('pydict','false')])
        pyformat=self.str2bool(pydict)

        self.beginOutput()
        
        for host in self.getHostnames(args):

            attrs = self.newdb.getHostAttrs(host)
            if attr:
                try:
                    self.addOutput(host, attrs[attr])
                except KeyError:
                    raise sunhpc.core.utils.CommandError('Attribute %s does not exist' % attr)
            elif pyformat:
                # i don't understand why but when you pass it to the
                # shell in this way no need to escape
                #attrs = sunhpc.core.utils.escapeStringForShell(str(attrs))
                self.addOutput(host, attrs)
            else:
                fmt="%s:%s"
                for key in sorted(attrs.keys()):
                    self.addOutput(host,
                        fmt % (key, attrs[key]))

        if pyformat:
            self.endOutput(padChar='',linesep='')
        else:
            self.endOutput(padChar='')

RollName = "base"
