#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# ############################################################################
# Copyright (c): 2020, Huawei Tech. Co., Ltd.
# FileName     : pssh
# Version      : Gauss
# Date         : 2019-12-31
# Description  : Parallel ssh to the set of nodes in hosts.txt.
#                 For each node, this essentially does an "ssh host command".
#                 from each remote node in a directory.
#                 Each output file in that directory will be named
#                 by the corresponding remote node's hostname or IP address.
# ############################################################################
try:
    import optparse
    import sys
    import shlex
    from TaskPool import TaskPool
    from TaskPool import read_host_file
except ImportError as e:
    sys.exit("[GAUSS-52200] : Unable to import module: %s." % str(e))

TIME_OUT = 0
PARALLEL_NUM = 32


def parse_command():
    """
    return: parser
    """
    parser = optparse.OptionParser(conflict_handler='resolve')
    parser.disable_interspersed_args()
    parser.usage = "%prog [OPTIONS] command"
    parser.epilog = "Example: pssh -H hostname 'id'"
    parser.add_option('-H', dest='hostname', action='append',
                      help='Nodes to be connected')
    parser.add_option('-h', dest='hostfile',
                      help='Host file with each line per node')
    parser.add_option('-t', dest='timeout', type='int',
                      help='Timeouts in seconds')
    parser.add_option('-p', dest='parallel', type='int',
                      help='Maximum number of parallel')
    parser.add_option('-o', dest='outdir', help='Output results folder')
    parser.add_option('-e', dest='errdir', help='Error results folder')
    parser.add_option('-P', dest='print', action='store_true',
                      help='Print output')
    parser.add_option('-s', dest='shellmode', action='store_true',
                      help='Output only execution results')
    parser.add_option('-x', dest='extra',
                      help='Extra command-line arguments')
    parser.add_option('-i', dest='inline', action='store_true',
                      help='aggregated output and error for each server')
    parser.add_option('-O', dest='opt', action='append',
                      help='Additional ssh parameters')
    return parser


def check_parse(parser_info):
    """
    :param parser_info: Parameter key-value pairs
    :return: NA
    """
    # set defaults parallel and timeout value
    defaults = dict(parallel=PARALLEL_NUM, timeout=TIME_OUT)
    parser_info.set_defaults(**defaults)
    opts_info, args_info = parser_info.parse_args()

    if not opts_info:
        parser_info.error("The commands is request.")
    if not opts_info.hostname and not opts_info.hostfile:
        parser_info.error("The host info is request.")

    return opts_info, args_info


def run(hosts):
    """
    function: do run process
    input : hosts
    output: NA
    """

    manager = TaskPool(opts)
    for host in hosts:
        cmd = ["ssh", host, '-n',
               "-o", "SendEnv=PSSH_NODENUM PSSH_HOST",
               "-o", "BatchMode=yes",
               "-o", "ConnectionAttempts=10",
               "-o", "ConnectTimeout=30",
               "-o", "NumberOfPasswordPrompts=1",
               "-o", "ServerAliveCountMax=10",
               "-o", "ServerAliveInterval=30",
               "-o", "TCPKeepAlive=yes"]
        if opts.extra:
            extraInfo = shlex.split(opts.extra)
            cmd.extend(extraInfo)
        if opts.opt:
            for i in opts.opt:
                cmd.append("-o")
                cmd.append(i)
        cmd.extend(args)
        manager.add_task(host, cmd)
    try:
        statuses = manager.start()
        if min(statuses) < 0:
            # At least one process was killed.
            sys.exit(3)
        for status in statuses:
            if status == 255 and not opts.shellmode:
                sys.exit(4)
        for status in statuses:
            if (status != 0 and not opts.shellmode):
                sys.exit(5)
            elif status != 0:
                sys.exit(status)

    except Exception as ex:
        print(str(ex))
        sys.exit(1)


if __name__ == "__main__":
    parsers = parse_command()
    opts, args = check_parse(parsers)
    if opts.hostfile:
        host_list = read_host_file(opts.hostfile)
    else:
        host_list = opts.hostname
    host_list = list(set(host_list))
    run(host_list)
