#!/usr/bin/python -tt
# by skvidal
# gplv2+
# return all the process owned or matching the username given



import sys
import func.overlord.client
from  func.utils import is_error
from optparse import OptionParser

def parse_args(args):
    parser = OptionParser(version = "1.0")
    parser.add_option('--host', default=[], action='append',
               help="hosts to act on, defaults to ALL")
    parser.add_option('--timeout', default=300, type='int',
               help='set the wait timeout for func commands')
    parser.add_option('--forks', default=40, type='int',
               help='set the number of forks to start up')
    parser.add_option('--hosts-from-file', default=None, dest="hostfile",
               help="read list of hosts from this file, if '-' read from stdin")
    (opts, args) = parser.parse_args(args)

    if opts.hostfile:
        hosts = []
        if opts.hostfile == '-':
            hosts = sys.stdin.readlines()
        else:
            hosts = open(opts.hostfile, 'r').readlines()
        
        for hn in hosts:
            hn = hn.strip()
            if hn.startswith('#'):
                continue
            hn = hn.replace('\n', '')
            opts.host.append(hn)
               

    return opts, args, parser


opts, args, parser = parse_args(sys.argv[1:])
    
if len(args) < 1:
    print parser.format_help()
    sys.exit(1)
    
username = args[0]

hosts ='*'
if opts.host:
    hosts = ';'.join(opts.host)

fc = func.overlord.client.Client(hosts, timeout=opts.timeout, nforks=opts.forks)

results = fc.process.grep(username)
for (hn, output) in results.items():
    if is_error(output):
        msg = 'Error: %s: ' % hn
        for item in output[1:3]:
            if type(item) == type(''):
                msg += ' %s' % item
        print >> sys.stderr, msg 
        continue

    for val in output.values():
        for line in val:
            if line.find('func') != -1: # if we're seeing the func process for any reason, skip it
                continue 
            print '%s:%s' % (hn, line)
        
                        
