#!/usr/bin/env python

# Copyright 2008-2009 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.
#


import sys
import traceback
import os
import time
import errno
import subprocess
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 vami_log

VAMI_SFCB_LOGFILENAME          = "/opt/vmware/var/log/vami/vami-sfcb.log"
VAMI_SCHEDULER_SLEEP_TIME_SECS = 120 # Bug 1624549 reduce sfcb timeout #300
VAMI_CORE_SERVICE_REG_FILE     = "/opt/vmware/var/lib/sfcb/stage/regs/VAMI_Internal.reg"
VAMI_CORE_SCHEDULER_NAME       = "VAMI_Scheduler"

log = None

def printHelp():
  errorMessage='Usage: ' + os.path.basename(sys.argv[0]) + ' <pid> '
  print (errorMessage)
  return

def main():
    global      log
    log = vami_log.logfile(VAMI_SFCB_LOGFILENAME)

    try:
        opts = (sys.argv[1:])
        if len(opts) == 0:
           printHelp()
           return 1

        log.message(vami_log.LOG_INFO, "Starting a new initialization script.");
        log.message(vami_log.LOG_INFO, "Pids passed in are " + ' '.join(opts) + ". Sleeping for %d (secs)." % (VAMI_SCHEDULER_SLEEP_TIME_SECS, ))

        # sleep for enough time, so that sfcb has time to start up
        # before we make the initialize call.
        # initialize is not a critical operation and can start after sometime
        time.sleep(VAMI_SCHEDULER_SLEEP_TIME_SECS)

        # check if the sfcbd processes referenced by pid's are running
        cmdList = ["ps", "-p", ' '.join(opts)]
        cmd = (' '.join(cmdList))
        pobj = os.popen(cmd)
        log.message(vami_log.LOG_INFO, "ran command: " + cmd)

        # check if the sfcb process which was passed in is still running
        count = 0
        while True:
            line = pobj.readline()
            if not line:
                break
            log.message(vami_log.LOG_INFO, "ps returned process: " + line)
            count = count + 1

        log.message(vami_log.LOG_INFO, "Number of sfcbd processes: %d" % (count-1, ))

        if(count > 1):
          found = False
          if(os.path.exists(VAMI_CORE_SERVICE_REG_FILE)):
              fd = open(VAMI_CORE_SERVICE_REG_FILE)
              while True:
                  line = fd.readline()
                  if not line:
                      break
                  if line.find(VAMI_CORE_SCHEDULER_NAME):
                      found = True
                      break;
              fd.close()

          if found == True:
              log.message(vami_log.LOG_INFO, "VAMI Scheduler provider is present on the system.")
          else:
              log.message(vami_log.WARNING, "VAMI Scheduler provider is not present on the system.")
              return 1

          rettuple = vami_cim_util.invokeNonStaticMethod('root/vami', 'VAMI_SchedulerService', 'StartService')
          if rettuple != None and len(rettuple) > 0 and rettuple[0] == 0:
              log.message(vami_log.LOG_INFO, "Success! Scheduler Service was started successfully.")
              return 0
          else:
              log.message(vami_log.LOG_ERROR, "Failed to start Scheduler Service. Return value is not zero.")
              return 1
        else:
          log.message(vami_log.LOG_WARNING, "Unable to start Scheduler Service. ",
                      "CIM server that started this script doesn't appear to be running.")
        return 1

    except:
        log.message(vami_log.LOG_ERROR, "Failed to start Scheduler Service. Unknown error.")
        log.message(vami_log.LOG_ERROR, traceback.format_exc())
        return 1


if __name__ == "__main__":
      ret = main()
      sys.exit(ret)
