#!/usr/bin/python
import logging
import os
import sys
import optparse
import jjobrun.configManager
from jjobrun.__version__ import version

def runJob(os,release):
    return 0


def main():
    reload(sys)
    sys.setdefaultencoding('utf-8')
    log = logging.getLogger("main")
    p = optparse.OptionParser(version = "%prog " + version)
    p.add_option('-v', '--verbose', action ='count',help='Change global log level, increasing log output.', metavar='LOGFILE')
    p.add_option('-q', '--quiet', action ='count',help='Change global log level, decreasing log output.', metavar='LOGFILE')
    p.add_option('--log-config', action ='store',help='Logfile configuration file, (overrides command line).', metavar='LOGFILE')
    p.add_option('--envvar', action ='append',help='Which enfiroment variables to whitelist.', metavar='ENVIROMENT_VAR')
    p.add_option('--dir-jobs', action ='append',help='directory storing json jobs.', metavar='DIR_JOB')
    p.add_option('--dir-scripts', action ='append',help='directory storing jobs scripts.', metavar='DIR_SCRIPT')
    
    
    options, arguments = p.parse_args()
    if options.log_config:
        if os.path.isfile(str(options.logfile)):
            logging.config.fileConfig(options.logfile)
        else:
            logging.basicConfig(level=logging.INFO)
            log = logging.getLogger("main")
            log.error("Logfile configuration file '%s' was not found." % (options.logfile))
            sys.exit(1)
    else:
        logging.basicConfig(level=logging.INFO)
    outputDict = None
    logFile = None
    envvardict = {}
    
    currentDir = os.path.dirname(os.path.realpath(__file__))
    envDir = ["%s/enviroments/" % (currentDir)]
    jobsDir = ["%s/jobs/" % (currentDir)]
    scriptsDir  = ["%s/transfer/" % (currentDir)]
    
    if 'VMCHNDL_ON_LOG_CONF' in os.environ:
        logFile = os.environ['VMCHNDL_ON_LOG_CONF']
    if 'CHROOT' in os.environ:
        log.error("CHROOT in environ")
        sys.exit(1)
    
    # Set up log file
    LoggingLevel = logging.WARNING
    LoggingLevelCounter = 2
    if options.verbose:
        LoggingLevelCounter = LoggingLevelCounter - options.verbose
        if options.verbose == 1:
            LoggingLevel = logging.INFO
        if options.verbose == 2:
            LoggingLevel = logging.DEBUG
    if options.quiet:
        LoggingLevelCounter = LoggingLevelCounter + options.quiet
    if LoggingLevelCounter <= 0:
        LoggingLevel = logging.DEBUG
    if LoggingLevelCounter == 1:
        LoggingLevel = logging.INFO
    if LoggingLevelCounter == 2:
        LoggingLevel = logging.WARNING
    if LoggingLevelCounter == 3:
        LoggingLevel = logging.ERROR
    if LoggingLevelCounter == 4:
        LoggingLevel = logging.FATAL
    if LoggingLevelCounter >= 5:
        LoggingLevel = logging.CRITICAL
    if options.log_config:
        logFile = options.log_config
    if logFile != None:
        if os.path.isfile(str(options.log_config)):
            logging.config.fileConfig(options.log_config)
        else:
            logging.basicConfig(level=LoggingLevel)
            log = logging.getLogger("main")
            log.error("Logfile configuration file '%s' was not found." % (options.log_config))
            sys.exit(1)
    else:
        logging.basicConfig(level=LoggingLevel)
    log = logging.getLogger("main")


    if options.envvar:
        for item in options.envvar:
            value = ""
            if  item in os.environ.keys():
                value = os.environ[item]
            finalvalue = value.strip()
            envvardict[item] = finalvalue

    if options.dir_jobs:
        jobsDir = options.dir_jobs

    if options.dir_scripts:
        scriptsDir = options.dir_scripts

    
    for item in envvardict.keys():
        if len(envvardict[item]) < 3 :
            log.warning("Enviroment variable '%s' is unset." % item)
        log.info("Matrix Enviroment values :%s=%s" % (item,envvardict[item]))
    if len(envvardict.keys()) == 0:
        log.error("No Enviroment variables set on the command line")
        sys.exit(4)
    
    log.debug("dirJobs=%s" % (jobsDir))
    runnerObj = jjobrun.configManager.matrixRunner(matrixEnv=envvardict,
        dirEnviroments=envDir,
        dirJobs=jobsDir,
        dirScripts=scriptsDir,
        )
    rc = runnerObj.loadconfig()
    if rc != True:
        log.error("Loading config failed")
        sys.exit(2)
    rc = runnerObj.Run(envvardict)
    if rc != 0:
        log.error("Running failed")
        sys.exit(rc)
if __name__ == '__main__':
    logging.basicConfig(level=logging.INFO)
    main()
