#!/usr/bin/python -tt


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=10, 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:])

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

fc = func.overlord.client.Client(hosts, timeout=opts.timeout, nforks=opts.forks)
results = fc.command.run('/bin/hostname -f')
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
    
    myname = output[1][:-1]
    if hn != myname:
        print "mismatch puppetname:%s does not match host known name: %s" % (hn, myname)


