#!/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.

import sys
import re
import socket
import time


def main():

    pRegex = re.compile('^\s*([^=\s]+)\s*=([^$]+)$')

    config = {}

    infoprovVersion = "1.1"
    hostname = socket.getfqdn()
    now = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
        
    conffile = None
    foundErr = False
    try:
        if len(sys.argv) <> 2:
            raise Exception("Usage: glite-ce-glue2-manager-static <config-file>")
            
        conffile = open(sys.argv[1])
        for line in conffile:
            parsed = pRegex.match(line)
            if parsed:
                config[parsed.group(1)] = parsed.group(2).strip(' \n\t"')
            else:
                tmps = line.strip()
                if len(tmps) > 0 and not tmps.startswith('#'):
                    raise Exception("Error parsing configuration file " + sys.argv[1])
    
        for mItem in ['ComputingServiceId',
                      'CE_BATCH_SYS',
                      'BATCH_VERSION',
                      'CECapabilities']:
            if not mItem in config:
                raise Exception("Missing attribute %s" % mItem)
        if not "EMIES" in config:
            config["EMIES"] = "no"
        if not "ESComputingServiceId" in config and config["EMIES"] == "yes":
            config["ESComputingServiceId"] = hostname + "_ESComputingElement"
    
    except Exception, ex:
        sys.stderr.write(str(ex) + '\n')
        foundErr = True

    if conffile:
        conffile.close()
    if foundErr:
        sys.exit(1)

    out = sys.stdout

    capaList = config["CECapabilities"].strip("()").split(',')
    
    srvList = [ config['ComputingServiceId'] ]
    if config['EMIES'] == 'yes':
        srvList.append(config['ESComputingServiceId'])
    
    for srvId in srvList:
        
        out.write("dn: GLUE2ManagerId=%s_Manager,GLUE2ServiceID=%s,GLUE2GroupID=resource,o=glue\n"
                    % (srvId, srvId))
        out.write("objectClass: GLUE2Entity\n")
        out.write("objectClass: GLUE2Manager\n")
        out.write("objectClass: GLUE2ComputingManager\n")

        out.write("GLUE2EntityCreationTime: %s\n" % now)
        out.write("GLUE2EntityName: Computing Manager on %s\n" % hostname)
        out.write("GLUE2EntityOtherInfo: InfoProviderName=glite-ce-glue2-manager-static\n")
        out.write("GLUE2EntityOtherInfo: InfoProviderVersion=%s\n" % infoprovVersion)
        out.write("GLUE2EntityOtherInfo: InfoProviderHost=%s\n" % hostname)
        for capaItem in capaList:
            out.write("GLUE2EntityOtherInfo: %s\n" % capaItem.strip())

        out.write("GLUE2ManagerID: %s_Manager\n" % srvId)
        out.write("GLUE2ManagerProductName: %s\n" % config['CE_BATCH_SYS'])
        out.write("GLUE2ManagerProductVersion: %s\n" % config['BATCH_VERSION'])
        out.write("GLUE2ManagerServiceForeignKey: %s\n" % srvId)

        if 'WorkingAreaShared' in config:
            out.write("GLUE2ComputingManagerWorkingAreaShared: %s\n" % config['WorkingAreaShared'].upper())
        if 'WorkingAreaGuaranteed' in config:
            out.write("GLUE2ComputingManagerWorkingAreaGuaranteed: %s\n" % config['WorkingAreaGuaranteed'].upper())
        if 'WorkingAreaTotal' in config:
            out.write("GLUE2ComputingManagerWorkingAreaTotal: %s\n" % config['WorkingAreaTotal'])
        if 'WorkingAreaFree' in config:
            out.write("GLUE2ComputingManagerWorkingAreaFree: %s\n" % config['WorkingAreaFree'])
        if 'WorkingAreaLifeTime' in config:
            out.write("GLUE2ComputingManagerWorkingAreaLifeTime: %s\n" % config['WorkingAreaLifeTime'])
        if 'WorkingAreaMultiSlotTotal' in config:
            out.write("GLUE2ComputingManagerWorkingAreaMultiSlotTotal: %s\n" % config['WorkingAreaMultiSlotTotal'])
        if 'WorkingAreaMultiSlotFree' in config:
            out.write("GLUE2ComputingManagerWorkingAreaMultiSlotFree: %s\n" % config['WorkingAreaMultiSlotFree'])
        if 'WorkingAreaMultiSlotLifeTime' in config:
            out.write("GLUE2ComputingManagerWorkingAreaMultiSlotLifeTime: %s\n" % config['WorkingAreaMultiSlotLifeTime'])
        out.write("GLUE2ComputingManagerComputingServiceForeignKey: %s\n" % srvId)
        out.write("\n")






if __name__ == "__main__":
    main()






