#coding:utf-8
import os
import sys
import sunhpc.invoke
import sunhpc.commands
class Command(sunhpc.commands.list.command):
    """
    The Help Command print the usage of all the registered
    Commands.
    
    <param optional='1' type='string' name='subdir'>
    Relative of Python commands for listing help.  This is used internally
    only.
    </param>
    
    <example cmd='list help'>
    List help for all commands
    </example>
    
    <example cmd='list help subdir=list/host'>
    List help for all commands under list/host
    </example>
    """

    def run(self, params, args):

        (subdir, cols) = self.fillParams([('subdir', ), ('cols', 80) ], params)
        if subdir:
            filepath = os.path.join(sunhpc.commands.__path__[0], subdir)
            modpath  = 'sunhpc.commands.%s' % '.'.join(subdir.split(os.sep))
        else:
            filepath = sunhpc.commands.__path__[0]
            modpath  = 'sunhpc.commands'
        
        tree = sunhpc.core.files.Tree(filepath)
        dirs = tree.getDirs()
        dirs.sort()

        if 'COLUMNS' in os.environ:
            cols = int(os.environ['COLUMNS'])
            
        for dir in dirs:
            if not dir: continue
                
            module = '%s.%s' % (modpath, '.'.join(dir.split(os.sep)))
            __import__(module)
            module = eval(module)
            
            try:
                o = getattr(module, 'Command')(None)
            except AttributeError:
                continue
        
            if o.MustBeRoot and not self.isRootUser():
                continue

            cmd = ' '.join(dir.split(os.sep))
            l   = len(cmd) + 1
            s   = ''
            for arg in o.usage().split():
                if l + len(arg) < cols or cols == 0:
                    s += '%s ' % arg
                    l += len(arg) + 1 # space
                else:
                    #s += '\n\t %s ' % arg
                    s += '\n%s %s ' % (" "*len(cmd), arg)
                    l  = len(arg) + 9 # tab + space

            self.addText('%s %s\n' % (cmd, s))

RollName = "base"
