#!/usr/bin/python

# (c) 2012, Michael DeHaan <michael.dehaan@gmail.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible.  If not, see <http://www.gnu.org/licenses/>.

try:
    import json
except ImportError:
    import simplejson as json

from optparse import OptionParser
import sys
import os
import getpass
import shlex
import ansible.runner
import ansible.playbook
import ansible.constants as C
from optparse import OptionParser

class Cli(object):

    def __init__(self):
        pass

    def runner(self):
        parser = OptionParser(usage = 'ansible <host-pattern> [options]')
        parser.add_option("-a", "--args", dest="module_args",
            help="module arguments", default=C.DEFAULT_MODULE_ARGS)
        parser.add_option('-f','--forks', dest='forks', default=C.DEFAULT_FORKS, type='int',
            help='number of parallel processes to use')
        parser.add_option("-i", "--inventory-file", dest="inventory",
           help="inventory host file", default=C.DEFAULT_HOST_LIST)
        parser.add_option("-k", "--ask-pass", default=False, action="store_true",
            help="ask for SSH password")
        parser.add_option("-M", "--module-path", dest="module_path",
           help="path to module library", default=C.DEFAULT_MODULE_PATH)
        parser.add_option("-m", "--module-name", dest="module_name",
            help="module name to execute", default=C.DEFAULT_MODULE_NAME)
        parser.add_option('-o', '--one-line', dest='one_line', action='store_true',
            help="condense output")
        parser.add_option('-t', '--tree', dest='tree', default=None,
            help="log output to this directory")
        parser.add_option('-T', '--timeout', default=C.DEFAULT_TIMEOUT, type='int',
            dest='timeout', help="set the SSH timeout in seconds")
        parser.add_option('-u', '--user', default=C.DEFAULT_REMOTE_USER,
            dest='remote_user', help='connect as this user')
        options, args = parser.parse_args()

        if len(args) == 0 or len(args) > 1:
            parser.print_help()
            sys.exit(1)
        pattern = args[0]

        sshpass = None
        if options.ask_pass:
            sshpass = getpass.getpass(prompt="SSH password: ")

        self.options = options

        runner = ansible.runner.Runner(
            module_name=options.module_name,
            module_path=options.module_path,
            module_args=shlex.split(options.module_args),
            remote_user=options.remote_user,
            remote_pass=sshpass,
            host_list=options.inventory,
            timeout=options.timeout,
            forks=options.forks,
            pattern=pattern,
            verbose=True,
        )
        return runner

    def output(self, results):

        # if specifying output destination (aka tree output saves), create the
        # directory to output to

        if results is None:
           print >> sys.stderr, "No hosts matched"
           sys.exit(1)

        options = self.options

        # TODO: split into function 
        if options.tree:
            if options.tree[0] != '/':
                options.tree = os.path.realpath(os.path.expanduser(options.tree))
            if not os.path.exists(options.tree):
                try:
                    os.makedirs(options.tree)
                except (IOError, OSError), e:
                    print >> sys.stderr, "Could not make dir %s: %s" % (options.tree, e)
                    sys.exit(1)
            if not os.access(options.tree, os.W_OK):
                print >> sys.stderr, "Cannot write to path %s" % options.tree
                sys.exit(1)

        # now walk results and print output

        module_name = self.options.module_name
        
        for hostname in sorted(results['contacted']):
            result    = results['contacted'][hostname]
            
            # TODO: refactor
            rc        = 0
            msg       = ''
            failed    = False
            stdout    = None
            stderr    = None
            traceback = None
            if type(result) == dict:
                failed    = result.get('failed', 0)
                msg       = result.get('msg', '')
                if module_name == 'command':
                    # TODO: refactor
                    rc        = result.get('rc',0)
                    stdout    = result.get('stdout', '')
                    stderr    = result.get('stderr', '')
                    traceback = result.get('traceback', '')

            if options.one_line:
                # try to print everything on one line, but don't strip newlines
                # if the command output happend to be too long
                if module_name == 'command':
                    if not failed:
                        buf = "(stdout) %s" % stdout
                        if stderr.rstrip() != '':
                            buf = "(stdout) %s (stderr) %s" % (stdout,stderr)
                        print "%s | rc=%s | %s" % (
                            hostname, rc, buf
                        )
                    else:
                        print "%s | (error) %s" % (hostname, msg)
                else:
                    print "%s | %s" % (hostname, result)
            else:
                # summarize response from command in multiple lines
                buf = ''
                if module_name == 'command':
                    if not failed:
                        buf += "%s | rc=%s >>\n" % (hostname, rc)
                    else:
                        buf += "%s | rc=%s | FAILED >>\n" % (hostname, rc)
                    buf += stdout
                    if stderr:
                        buf += stderr
                    if msg:
                        buf += msg
                    print buf
                else:
                    if not failed:
                        buf += "%s >>" % hostname
                    else:
                        buf += "%s | FAILED >>" % hostname
                    buf += json.dumps(result, indent=4, sort_keys=True)
                if options.tree:
                    path = os.path.join(options.tree, hostname)
                    fd = open(path, "w+")
                    fd.write(buf)
                    fd.close()

        if len(results['dark'].keys()) > 0:
            print >> sys.stderr, "*** Hosts which could not be contacted or did not respond: ***"
            failed_hosts = results['dark'].keys()
            for hostname in failed_hosts:
                print >> sys.stderr, "%s:\n%s\n" % (hostname, results['dark'][hostname])
            print ""

if __name__ == '__main__':
    cli = Cli()
    cli.output(cli.runner().run())
    
