#! /usr/bin/python3 -s
#
# Copyright (c) 2013-2021 - 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

# Force sys.stdout to be unbuffered w/o using the python -u option, which
# does not always work as #!/usr/bin/env python -u
# Solution from:
# https://stackoverflow.com/questions/107705/disable-output-buffering

import gc
import importlib
import json
import os
import argparse
import traceback
import sys

import etce.loader
import etce.utils
from etce.config import ConfigDictionary
from etce.platform import Platform, platform_suffix_list
from etce.sshclient import SSHClient

#gc.garbage.append(sys.stdout)
#sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)

def sendreturnandexit(isexception,
                      result):
    tracebackmsg = ''
    if isexception:
        tracebackmsg = traceback.format_exc()
    print(SSHClient.RETURNVALUE_OPEN_DEMARCATOR)
    print(json.dumps({ 'isexception':isexception, 'result':result, 'traceback':tracebackmsg }))
    print(SSHClient.RETURNVALUE_CLOSE_DEMARCATOR)
    sys.stdout.flush()

    if(isexception):
        sys.exit(1)
    else:
        sys.exit(0)


usagestr = '''
description: Dynamically loads and runs the Python method:

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

             where modulename specifies a Python module found in the
             "etce" package.

             etce-field-exec is not intended to be called directly. It
             is invoked by other etce applications over an SSH connection on
             field nodes to perform work.
'''
parser = argparse.ArgumentParser(description=usagestr,
                                 formatter_class=argparse.RawDescriptionHelpFormatter)

parser.add_argument('--cwd',
                    action='store',
                    default='',
                    help='''Specifies the subdirectory under the WORK_DIRECTORY configuration
                    root directory where etce will switch to before executing
                    the named method. Default is just WORK_DIRECTORY itself''')
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.''')

args = parser.parse_args()

config = etce.config.ConfigDictionary()

verbose = config.get('etce', 'VERBOSE').upper() == 'ON'

ret = ''

# determinte the subdirectory under WORK_DIRECTORY to run from
etcedir = ConfigDictionary().get('etce', 'WORK_DIRECTORY')

while args.cwd.find('/') == 0:
    args.cwd = args.cwd[1:]

if '..' in args.cwd.split('/'):
    sendreturnandexit(True, '".." not permitted in working directory name')

if '.' in args.cwd.split('/'):
    if args.cwd == '.':
        args.cwd = ''
    else:
        sendreturnandexit(True, '"." not permitted in working directory name')

# switch to working dir
workingdir = etcedir

if len(args.cwd) > 0:
    workingdir = os.path.join(etcedir, args.cwd)

if not os.path.exists(workingdir):
    hostname = Platform().hostname()
    print('Creating working directory "%s" on host "%s"' % (workingdir, hostname))
    os.makedirs(workingdir)

if not os.path.isdir(workingdir):
    hostname = Platform().hostname()
    sendreturnandexit(True,
                      'Working directory path "%s" exists on host "%s" but ' \
                      'is not a directory. Quitting.' % (workingdir, hostname))

os.chdir(workingdir)

if verbose:
    print('etce: Running from %s' % workingdir)

try:
    method = etce.loader.load_etce_method(args.modulename,
                                          args.methodname,
                                          platform_suffix_list())

    if method:
        if len(args.methodargs) == 2:
            if verbose:
                print("(%s,%s)" % (args.modulename, args.methodname))
            ret = method()
        else:
            if verbose:
                print("(%s,%s,%s)" % \
                    (args.modulename, args.methodname, ' '.join(args.methodargs)))

            typedargs = [ etce.utils.configstrtoval(arg) for arg in args.methodargs ]

            ret = method(*typedargs)

    else:
        sendreturnandexit(True, 'Module(%s) or method(%s) not found.' \
                          % (args.modulename, args.methodname))

    sendreturnandexit(False, ret)

except Exception as e:
    sendreturnandexit(True, str(e))
