#!/usr/bin/python
# Copyright (c) Members of the EGEE Collaboration. 2004. 
# See http://www.eu-egee.org/partners/ for details on the copyright
# holders.  
#
# Licensed under the Apache License, Version 2.0 (the "License"); 
# you may not use this file except in compliance with the License. 
# You may obtain a copy of the License at 
#
#     http://www.apache.org/licenses/LICENSE-2.0 
#
# Unless required by applicable law or agreed to in writing, software 
# distributed under the License is distributed on an "AS IS" BASIS, 
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
# See the License for the specific language governing permissions and 
# limitations under the License.

# plugin for gip framework.  generates Glue values associated
# with the scheduler, like FreeSlots or *ResponseTime

import sys
import os
import getopt
import string
import logging
import logging.config

from DynamicSchedulerGeneric import Analyzer
from DynamicSchedulerGeneric import GLUE1Handler
from DynamicSchedulerGeneric import GLUE2Handler
from DynamicSchedulerGeneric import Utils as DynSchedUtils


def main():

    try:
        opts, args = getopt.getopt(sys.argv[1:], "hc:", ["help", "config="])
    except getopt.GetoptError:
        sys.exit(1)

    cfgfile = None

    for opt_name, opt_arg in opts:
        if opt_name in ("-c", "--config"):
            cfgfile = opt_arg
        if opt_name in ("-h", "--help"):
            print """Usage: lcg-info-dynamic-scheduler -c <cfg_file>
The executable returns the following codes:
  0 Execution correctly performed
  1 Command line parser error (no message on standard error)
  2 Missing configuration file path (no message on standard error)
  3 Configuration parser error (messages on log)
  4 Execution error (messages on log)
"""
    if not cfgfile:
        sys.exit(2)
    
    try:
    
        logging.config.fileConfig(cfgfile)
        logger = logging.getLogger("lcg-info-dynamic-scheduler")

    except Exception, conf_log_err:
        logging.basicConfig(stream=sys.stderr)
        logger = logging.getLogger("lcg-info-dynamic-scheduler")
    
    config = None
    try:

        config = DynSchedUtils.readConfigurationFromFile(cfgfile)
            
    except Exception, config_error:
        logger.error("Cannot parse configuration file %s: %s" % (cfgfile, repr(config_err)))
        sys.exit(3)
    
    try:
    
        mjobTable = DynSchedUtils.getMaxJobsTable(config)
        collector = Analyzer.analyze(config, mjobTable)

        outputformat = config.get('Main','outfmtcode')    
        if  DynSchedUtils.GLUE1FORMAT in outputformat:
            GLUE1Handler.process(config, collector)
    
        if DynSchedUtils.GLUE2FORMAT in outputformat:
            GLUE2Handler.process(config, collector)
            
    except Exception, exec_error:
        logger.error("Execution error: %s" % str(exec_error))
        sys.exit(4)

if __name__ == "__main__":
    main()
