import platform
import sys
import logging
import os
import paramiko
import argparse
import json
import time

#########Logging configuration##########
here = os.path.abspath(os.path.dirname(__file__))
if platform.platform().startswith('Windows'):
    logging_file = os.path.join(here, os.path.splitext(
        os.path.basename(__file__))[0]+'.log')
else:
    logging_file = os.path.join(here, os.path.splitext(
        os.path.basename(__file__))[0]+'.log')

log_formatter = logging.Formatter(
    '%(asctime)s : %(levelname)s : %(threadName)-9s : %(message)s')
LOG = logging.getLogger(__name__)
LOG.setLevel(logging.DEBUG)

fileHandler = logging.FileHandler(logging_file)
fileHandler.setFormatter(log_formatter)
fileHandler.setLevel(logging.DEBUG)
LOG.addHandler(fileHandler)

consoleHandler = logging.StreamHandler(sys.stdout)
consoleHandler.setFormatter(log_formatter)
consoleHandler.setLevel(logging.DEBUG)
LOG.addHandler(consoleHandler)
#########Logging configuration ends##########
__version__ = "1.0"


def jsondata_parser(json_file):
    with open(json_file) as fd:
        if json_file.endswith(".json"):
            try:
                json_data = json.load(fd)
                return json_data
            except:
                LOG.exception("Parsing config file: {}".format(json_file))
                return None
    return None


class SSH:
    """
    simplifies ssh to ssh server
    """

    def __init__(self, ip, username, pwd, port=22):
        self.ip = ip
        self.user = username
        self.pwd = pwd
        self.port = port
        self.ssh_client = None
        self.terminal = None

    def connect(self):
        LOG.debug("Trying to connect {} as {}".format(self.ip, self.user))
        try:
            ssh_client = paramiko.SSHClient()
            ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            ssh_client.connect(self.ip, self.port, self.user, self.pwd)
            LOG.debug("Connected to {}".format(self.ip))
            self.ssh_client = ssh_client

            remote = self.ssh_client.invoke_shell()
            self.terminal = remote
        except paramiko.ssh_exception.AuthenticationException:
            LOG.exception(
                "Authentication failed when connecting to {}".format(self.ip))
            exit(1)
        except Exception as e:
            LOG.exception(
                "Could not SSH to {}, reason: {}".format(self.ip, str(e)))

    def execute_command(self, cmd):
        if self.ssh_client:
            LOG.debug("executing cmd: {}".format(cmd))
            try:
                while not self.terminal.send_ready():
                    time.sleep(1)
                self.terminal.send(cmd)

                while not self.terminal.recv_ready():
                    time.sleep(1)

                output = self.terminal.recv(9999)
                LOG.debug("command output: \n{}".format(output))
            except paramiko.ssh_exception.SSHException:
                LOG.exception("Failed to run command")

            return output

    def close_ssh(self):
        LOG.debug("Closing SSH connection")
        if self.ssh_client:
            self.ssh_client.close()


def perform_ssh(ssh_list):
    for target in ssh_list["SSH Servers"]:
        if target["ignore"] == "True":
            continue
        client = SSH(target["host"], target["user"], target["password"])
        client.connect()
        for command in target['commands']:
            client.execute_command(command)
        client.close_ssh()


def main(arg):
    if not os.path.exists(arg.conf):
        logging.error("{} doesn't exist".format(arg.conf))
        return

    config_data = jsondata_parser(arg.conf)

    if not config_data:
        logging.error(
            "No configuration found in json: (). Exiting.".format(arg.conf))
        return

    perform_ssh(config_data)


if __name__ == "__main__":
    """
        Execution starts here.
    """

    parser = argparse.ArgumentParser(description='Run commands over SSH')
    parser.add_argument('-c', '--conf', help='config', type=str, required=True)
    args = parser.parse_args()

    main(args)
