#!/usr/bin/env python

# Copyright 2008-2011 VMware, Inc.  All rights reserved.
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
from __future__ import print_function

import os
import sys
import time
import getopt

sys.path.append("/opt/vmware/lib/python/site-packages/")
import pywbem

sys.path.append("/opt/vmware/share/vami/")
import vami_cim_util

import gettext
__t = gettext.translation('vami_invoke_method', '/opt/vmware/lib/locale', fallback=True)
_ = __t.ugettext if sys.version_info[0] < 3 else __t.gettext


__defaultnamespace__ = 'root/cimv2'

__exit_error__      = 1
__exit_cli_error__  = 2

class vamiError:
  _message=""
  _code=0
  def __init__(self, newCode=0, newMessage=""):
    self.code    = newCode
    self.message = newMessage

  def __str__(self):
    return self.message

  def getCode(self):
    return self.code


def printHelp():
  errorMessage=_('Usage: ') + os.path.basename(sys.argv[0]) + \
  ' [-t <static|instance>  -n <namespace>] -c <classname> -m <methodname> |' + \
  ' -h help\n'
  errorMessage+= _('  -n (namespace) defaults to \'root/cimv2\'\n')
  errorMessage+= _('  -t (type) defaults to instance, specifying instance will invoke \n')+ \
                 _('   this method for all available instances\n')
  raise vamiError(__exit_cli_error__, errorMessage)


def main():
    try:
        opts = (sys.argv[1:])
    except:
        print (str(err))
        printHelp()

    if len(opts) == 0:
        printHelp()

    type = ''
    className = ''
    methodName = ''
    namespace = ''

    for i in range(0, len(opts), 2):
      if (len(opts) <= i+1):
        printHelp()
      if opts[i] in ("-h", "--help"):
        printHelp()
      elif opts[i] in ("-t", "--type"):
        type = opts[i+1]
      elif opts[i] in ("-c", "--classname"):
        className = opts[i+1]
      elif opts[i] in ("-m", "--methodname"):
        methodName = opts[i+1]
      elif opts[i] in ("-n", "--namespace"):
        namespace = opts[i+1]
      else:
        printHelp()

    if len(className) == 0 or len(methodName) == 0:
      print (_("\n***classname and methodname are required parameters***"))
      printHelp()

    if len(namespace) == 0:
      namespace = __defaultnamespace__

    try:
      if type == "static":
        rettuple = vami_cim_util.invokeStaticMethod (namespace,
                                                     className,
                                                     methodName)
      elif type == "instance" or len(type) == 0:
        rettuple = vami_cim_util.invokeNonStaticMethod (namespace,
                                                        className,
                                                        methodName)
      else:
        printHelp()
    except TypeError as e:
      raise vamiError(__exit_error__, e)
    except pywbem.CIMError as exc:
      (num, msg) = exc.args
      print (_("Please ensure that sfcbd is running"))
      if msg[0] != pywbem.CIM_ERR_NOT_SUPPORTED:
        raise vamiError(__exit_error__, _("Failure:") + msg)
      else:
        raise vamiError(__exit_error__, _("Failure: Unknown CIM error"))
    if len(rettuple) > 0:
        print (methodName + ':', end=' ')
        print (rettuple [0])

if __name__ == "__main__":
    try:
      main()
    except vamiError as error:
      print (error)
      sys.exit(error.getCode())
    except:
      print (_('\nFailure: Unknown Error'))
      sys.exit(__exit_error__)
