#!/usr/bin/env python

"""
Generates an aggregate config file.
Components (can) have a DefaultConfig.py file in their top
directory. This command retrieves all of them and merges them
together into one big configuration file that operators can then
edit.
"""
from __future__ import print_function

__revision__ = "$Id: wmcore-new-config,v 1.5 2010/01/22 22:08:32 sryu Exp $"
__version__ = "$Revision: 1.5 $"
__author__ = "fvlingen@caltech.edu"

import getopt
import os
import sys

from WMCore.Agent.Configuration import Configuration
from WMCore.Configuration import loadConfigurationFile
from WMCore.Configuration import saveConfigurationFile

def usage():
    msg = """
Generates an aggregate config file. Components (can) have a DefaultConfig.py 
file in their top directory. This command retrieves all of them and merges them
 together into one big configuration file that operators can then edit.

Usage: wmcore-new-config --roots=<list of comma separated directories> 
--output=<file for saving configuration>

"""
    print(msg)

# try to extract file from the command line
valid = ["roots=","output="]

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

if len(opts) == 0:
    usage()
    sys.exit(1)

roots = None
outputFile = None

for opt, arg in opts:
    if opt == '--roots':
        roots = arg.split(',')
    if opt == '--output':
        outputFile = arg

if roots == None:
    msg = """
Please set root directories for DefaultConfig.py discovery.
"""
    print(msg)
    usage()
    sys.exit(1)

if outputFile == None:
    msg = """
Please set output file for aggregated config file to be saved.
"""
    print(msg)
    usage()
    sys.exit(1)



config = Configuration()
config.section_('General')
config.General.document_("General Settings Section")
config.General.workDir = '/tmp/application'

msg = """
dialect: Choose between oracle or mysql
socket:  Set the socket file location for mysql (optional)
"""

config.section_("CoreDatabase")
config.CoreDatabase.document_(msg)
config.CoreDatabase.socket = '..../mysqldata/mysql.sock'
config.CoreDatabase.connectUrl = 'mysql://username:password@hostname/database_name'

for root in roots:
    # find the DefaultConfig.py files.
    for topdir, dirs, files in os.walk(root, topdown=False):
        for name in files:
            if name == 'DefaultConfig.py':
                location = os.path.join(topdir, name)
                config_section = loadConfigurationFile(location)
                print('adding: '+location)
                for component in config_section.listComponents_():
                    compAttr = config_section.component_(component)
                    compAttr.ComponentDir = os.path.join(config.General.workDir, component)
                    config.component_(component)
                config += config_section


saveConfigurationFile(config, outputFile, comment = True)


