#! /usr/bin/python3
#
# Copyright (c) 2019 - Adjacent Link LLC, Bridgewater, New Jersey
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
#   notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
#   notice, this list of conditions and the following disclaimer in
#   the documentation and/or other materials provided with the
#   distribution.
# * Neither the name of Adjacent Link LLC nor the names of its
#   contributors may be used to endorse or promote products derived
#   from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#

from __future__ import absolute_import, division, print_function
import argparse
import os
import pwd
import sys

from etce.field import Field
from etce.clientbuilder import ClientBuilder
from etce.fieldconnectionerror import FieldConnectionError

usagestr = '''
description: Connect to each specified host to verify SSH configuration.
             Add host key to known_hosts as needed and permitted.
'''

parser = argparse.ArgumentParser(description=usagestr,
                                 formatter_class=argparse.RawDescriptionHelpFormatter)

parser.add_argument('--user',
                    action='store',
                    default=None,
                    help='''Execute the command as user. This defaults to
                    the value of "SSH_USER" specified in the [etce]
                    section of the etceconf file, if specified. If
                    not, the current user is used.''')
parser.add_argument('--port',
                    action='store',
                    type=int,
                    default=None,
                    help='''Connect to remote field via specified port.
                    This defaults to the etce.conf "SSH_PORT" value.''')
parser.add_argument('--sshkey',
                    metavar='KEYFILE',
                    default=None,
                    help='''The SSH key file to use for connecting to
                    test hosts. If KEYFILE is not an absolute filename
                    it is assumed to be a keyfile in ~/.ssh. When not
                    specified, ETCE tries to determine the appropriate
                    key to use for each host by inspecting
                    ~/.ssh/config. If that fails, it will use the
                    default RSA key ~/.ssh/id_rsa if it exists.''')
parser.add_argument('--envfile',
                    action='store',
                    default=None,
                    help='''Envirorment file to invoke on remove nodes
                    before running the specified command.
                    default: None.''')
parser.add_argument('hostarg',
                    metavar='HOSTARG',
                    nargs='+',
                    action='store',
                    help='''Each HOSTARG is either an ETCE Host File
                    or a host name. All of the hosts specified are combined
                    into a single set and tested for SSH connectivity.''')

args = parser.parse_args()

hosts = set([])

for hostarg in args.hostarg:
   if os.path.exists(hostarg) and os.path.isfile(hostarg):
      hosts = hosts.union(Field(hostarg).allnodes())
   else:
      hosts.add(hostarg)

commandstr = 'platform hostname'

client = None

try:
   client = ClientBuilder().build(hosts,
                                  user=args.user,
                                  port=args.port,
                                  sshkey=args.sshkey,
                                  envfile=args.envfile)


   print()
   print('Attempting connection:')
   print('===')
   ret = client.execute(commandstr, hosts)

   for host in sorted(ret):
      print('Connected: %s' % (ret[host].retval['result']))
   print()

except FieldConnectionError as fe:
   print(str(fe), file=sys.stderr)
finally:
   if client:
      client.close()
