#!/usr/bin/python -tt
# by skvidal
# gplv2+


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

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('--grep-options', default='-n', dest='grep_options',
               help='set options to pass to grep "-r -i" for example')
    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) < 2:
    print parser.format_help()
    sys.exit(1)
    
search_str = args[0]
search_where = args[1:]

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

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

cmd = '/bin/grep %s %s %s' % (opts.grep_options, search_str, ' '.join(search_where))
print cmd
results = fc.command.run(cmd)
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 line in output[1].split('\n'):
        line  = line.strip()
        if not line:
            continue
        print '%s:%s' % (hn, line)
        
                        
