#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import signal
import sys
import tomahawk_bootstrap

# Add TOMAHAWK_HOME, TOMAHAWK_HOME/lib to sys.path
parent, bin_dir = tomahawk_bootstrap.set_lib_path(__file__)

import argparse
from tomahawk.command_line import Context
from tomahawk.constants import (
    VERSION,
    DEFAULT_TIMEOUT,
    DEFAULT_EXPECT_DELAY,
    DEFAULT_EXPECT_ENCODING
)
from tomahawk.log import create_logger
from tomahawk.main import Main

def create_argument_parser():
    p = argparse.ArgumentParser(
        prog = os.path.basename(__file__),
        description = 'A simple command executor for many hosts.',
        conflict_handler = 'resolve'
    )

    p.add_argument(
        'command', metavar='command', nargs='+',
        help='Command executed on remote hosts.',
    )
    p.add_argument(
        '-h', '--hosts', metavar='HOSTS',
        help='Host names for sending commands. (splited with ",")',
    )
    p.add_argument(
        '-f', '--hosts-files', metavar='HOST_FILE',
        help='Hosts files which listed host names. (splited with ",")'
    )
    p.add_argument(
        '--ssh', default='ssh', help='ssh program. (default: "ssh")'
    )
    p.add_argument(
        '-u', '--ssh-user', help='ssh user.'
    )
    p.add_argument(
        '-o', '--ssh-options', help='ssh options.'
    )
    p.add_argument(
        '-c', '--continue-on-error', action='store_true', default=None,
        help='Command exectuion continues whatever any errors.'
    )
    p.add_argument(
        '-p', '--parallel', metavar='NUM', type=int, default=1,
        help='Process numbers for parallel command execution. (default: 1)'
    )
    p.add_argument(
        '-l', '--prompt-login-password', action='store_true',
        help='Prompt a password for ssh authentication.'
    )
    p.add_argument(
        '-s', '--prompt-sudo-password', action='store_true',
        help='Prompt a password for sudo.'
    )
    p.add_argument(
        '--no-sudo-password', action='store_true',
        help='Never prompt a password for sudo.'
    )
    p.add_argument(
        '-t', '--timeout', metavar='SECONDS', type=int, default=DEFAULT_TIMEOUT,
        help='Specify expect timeout in seconds. (default: %d)' % (DEFAULT_TIMEOUT)
    )
    p.add_argument(
        '--expect-timeout', metavar='SECONDS', type=int,
        help='Duplicated. Use --timeout'
    )
    p.add_argument(
        '--expect-encoding', metavar='ENCODING', default=DEFAULT_EXPECT_ENCODING,
        help='Expect encoding for password prompt. (default: %s)' % (DEFAULT_EXPECT_ENCODING)
    )
    p.add_argument(
        '-d', '--delay', type=int, default=0,
        help='Command delay time in seconds. (default: 0)'
    )
    p.add_argument(
        '--expect-delay', type=float, default=DEFAULT_EXPECT_DELAY,
        help='Expect delay time in seconds. (default: 0.05)'
    )
    p.add_argument(
        '-D', '--debug', action='store_true', default=False,
        help='Enable debug output.',
    )
    p.add_argument(
        '--profile', action='store_true', help='Enable profiling.'
    )
    p.add_argument(
        '--version', action='version', version='%(prog)s ' + VERSION
    )
    return p

if __name__ == '__main__':
#    TODO: 
#    Main(__file__, bin_dir).run()
    try:
        arg_parser = create_argument_parser()
        options = arg_parser.parse_args()
        log = create_logger(options.debug)
        log.debug('options = ' + str(options))
        log.debug('arguments = ' + str(options.command))
        context = Context(
            bin_dir,
            options.command,
            options.__dict__,
            arg_parser,
        )
    
        if options.profile:
            file = 'tomahawk.prof.%d' % (os.getpid())
            cProfile = __import__('cProfile')
            pstats = __import__('pstats')
            prof = cProfile.run("Main(context, log).run()", file)
            p = pstats.Stats(file)
            p.strip_dirs()
            p.sort_stats('time', 'calls')
            p.print_stats()
        else:
            sys.exit(Main(context, log).run())
    except KeyboardInterrupt:
        print
        print("Keyboard interrupt.")

