#!/usr/bin/env python
"""
_inject-to-config-cache_

Add a config and it's meta data to the config cache.
"""

import os
import sys
import importlib

from PSetTweaks.WMTweak import makeTweak
from WMCore.Cache.WMConfigCache import ConfigCache

def loadConfig(configPath):
    """
    _loadConfig_

    Import a config.
    """
    print("Importing the config, this may take a while...", end=' ')
    sys.stdout.flush()
    cfgBaseName = os.path.basename(configPath).replace(".py", "")
    cfgDirName = os.path.dirname(configPath)
    modSpecs = importlib.machinery.PathFinder().find_spec(cfgBaseName, [cfgDirName])
    module = modSpecs.loader.load_module()

    print("done.")
    return module

def main():
    """
    Main function of the module
    """
    if len(sys.argv) != 8:
        print("Usage: %s couchUrl database_name user_name group_name input_file label description" % sys.argv[0])
        sys.exit(1)

    if not os.path.exists(sys.argv[5]):
        print("Error: Can't locate config file.")
        sys.exit(1)

    loadedConfig = loadConfig(sys.argv[5])

    configCache = ConfigCache(sys.argv[1], sys.argv[2])
    configCache.createUserGroup(sys.argv[4], sys.argv[3])
    configCache.addConfig(sys.argv[5])
    configCache.setPSetTweaks(makeTweak(loadedConfig.process).jsondictionary())
    configCache.setLabel(sys.argv[6])
    configCache.setDescription(sys.argv[7])
    configCache.save()

    print("Added file to the config cache:")
    print("  DocID:    %s" % configCache.document["_id"])
    print("  Revision: %s" % configCache.document["_rev"])
    sys.exit(0)

if __name__ == "__main__":
    main()
