#!/usr/bin/env python
#
# Copyright (c) 2013-2017 - 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.
#

import argparse
import os
import pwd
import sys

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


usagestr = '''
description: runs the python function

             modulename.methodname(methodarg1, methodarg2, ...).

             on the specified field. modulename is a module found in 
             the python etce package subdirectory tree in the field 
             members' python library path. 
'''

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

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('--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('--workingdir',
                    action='store',
                    default='.',
                    help='''Specifies the subdirectory under the 
                    "WORK_DIRECTORY" on the remote to before 
                    executing the command. The default 
                    "." means switch to WORK_DIRECTORY.''')
parser.add_argument('modulename',
                    metavar='MODULENAME',
                    action='store',
                    help='''A module found in the python etce package
                    on the remote host.''')
parser.add_argument('methodname',
                    metavar='METHODNAME',
                    action='store',
                    help='''The method from module to invoke. The method
                    must either be defined at the top level of the target
                    module, or as a method of a class with name that matches
                    the module name (for example a class MyModule in mymodule.py.''')
parser.add_argument('methodargs',
                    metavar='METHODARGS',
                    nargs='*',
                    action='store',
                    help='''The arguments to the method being invoked.''')
parser.add_argument('hostfile',
                    metavar='HOSTFILE',
                    action='store',
                    help='''The ETCE Host file containing the 
                    node names from which the remote source 
                    directories are collected.''')

args = parser.parse_args()

if not os.path.exists(args.hostfile):
   print >>sys.stderr, 'Cannot find hostfile "%s". Quitting' % args.hostfile
   exit(1)
   
hosts = Field(args.hostfile).leaves()

commandstr = '%s %s %s' % (args.modulename, args.methodname, ' '.join(args.methodargs))

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

try:
   print commandstr

   ret = client.execute(commandstr, hosts, workingdir=args.workingdir)

   for k in ret:
      print '[%s] return: %s' % (k, ret[k].retval['result'])

finally:
   client.close()
