#!/usr/bin/env python

"""
Controls the daemons that represent the components.

The following is a short a set of commands you can give to start
and control the daemons:

# generates a config file based on the root dirs (it looks for DefaultConfig.py files):
# the component sections need a namespace attribute to the class can be loaded and daemonized.
wmcore-new-config --roots=src/python/WMComponent/ErrorHandler/,src/python/WMComponent/DBS3Buffer/ --output=WMCoreConfig.py

#edit the generated config file to fit your needs.

# loads default tables and tables from a specific module. The backend is automatically selected based on the config file.
wmcore-db-init --config=WMCoreConfig.py --create --modules=WMComponent.DBS3Buffer.Database 

# start the daemons from components defined in the config file:
wmcoreD --start --config=WMCoreConfig.py

# prints status of components
wmcoreD --status --config=WMCoreConfig.py

# restarts components
wmcoreD --restart --config=WMCoreConfig.py

# shutdown the daemons:
wmcoreD --shutdown --config=WMCoreConfig.py --cleanup-all

"""

from builtins import str
__revision__ = "$Id: wmcoreD,v 1.16 2010/05/26 21:09:35 sfoulkes Exp $"
__version__ = "$Revision: 1.16 $"
__author__ = "fvlingen@caltech.edu"

import getopt
import os
import subprocess
import sys
import time
import json
import psutil
import logging

from Utils.wmcoreDTools import connectionTest, startup, shutdown, status, restart
from WMCore.Configuration import loadConfigurationFile

# FORMAT = "%(asctime)s:%(levelname)s:%(module)s:%(funcName)s(): %(message)s"
FORMAT = "%(message)s"
LOGLEVEL = logging.INFO

logStdoutHandler = logging.StreamHandler(sys.stdout)
logging.basicConfig(handlers=[logStdoutHandler], format=FORMAT, level=LOGLEVEL)

def usage():

    msg = """
Usage: wmcoreD <--start|--shutdown|--status> --config <opts>

You must provide either --start OR --shutdown OR --status

You must either set the WMAGENT_CONFIG environment variable or specify the config file with
--config

--start starts up the components
--shutdown shutsdown the components
--status prints the status of the components
--restart restarts components

options:
--cleanup-logs purges logs
--cleanup-all purges component dirs

"""
    logging.info(msg)


valid = ['config=', 'start', 'shutdown', 'status', 'restart',
         'components=', 'cleanup-logs', 'cleanup-all']

try:
    opts, args = getopt.getopt(sys.argv[1:], "", valid)
except getopt.GetoptError as ex:
    logging.error(str(ex))
    usage()
    sys.exit(1)

config = None
command = None
doLogCleanup = False
doDirCleanup = False
componentsList = None


for opt, arg in opts:
    if opt == "--config":
        config = arg
    if opt == "--start":
        if command != None:
            logging.error("Command specified twice:\n")
            usage()
            sys.exit(1)
        command = "start"
    if opt == "--shutdown":
        if command != None:
            logging.error("Command specified twice:\n")
            usage()
            sys.exit(1)
        command = "shutdown"
    if opt == "--status":
        if command != None:
            logging.error("Command specified twice:\n")
            usage()
            sys.exit(1)
        command = "status"
    if opt == "--restart":
        if command != None:
            logging.error("Command specified twice:\n")
            usage()
            sys.exit(1)
        command = "restart"
    if opt == "--cleanup-logs":
        doLogCleanup = True
    if opt == "--cleanup-all":
        doDirCleanup = True
    if opt == "--components":
        compList = arg.split(',')
        componentsList = []
        for item in compList:
            if item.strip == "":
                continue
            componentsList.append(item)

if command == None:
    msg = "No command specified\n"
    logging.error(msg)
    usage()
    sys.exit(1)

if config == None:
    config = os.environ.get("WMAGENT_CONFIG", None)

    if config == None:
        msg = "No Config file provided\n"
        msg += "provide one with the --config option"
        logging.error(msg)
        usage()
        sys.exit(1)

if not os.path.exists(config):
    logging.error("Can't find config: %s" % config)
    sys.exit(1)

# load the config file here.
cfgObject = loadConfigurationFile(config)
#workingDir = os.path.expandvars(workingDir)

if componentsList != None:
    msg = "Components List Specified:\n"
    msg += str(componentsList).replace('\'', '')
    logging.info(msg)

if command == "start":
    connectionTest(config)
    exitCode = startup(config, componentsList)
    sys.exit(exitCode)
elif command == "shutdown":
    connectionTest(config)
    exitCode = shutdown(config, componentsList, doDirCleanup, doLogCleanup)
    sys.exit(exitCode)
elif command == "status":
    connectionTest(config)
    exitCode = status(config, componentsList)
    sys.exit(exitCode)
elif command == "restart":
    connectionTest(config)
    exitCode = restart(config, componentsList, doDirCleanup, doLogCleanup)
    sys.exit(exitCode)

