#!/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-computingservice-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 ['SiteId',
                      'ComputingServiceId',
                      'Shares',
                      'ExecutionEnvironments']:
            if not mItem in config:
                raise Exception("Missing attribute %s" % mItem)
            
        if not "EMIES" in config:
            config["EMIES"] = "no"
        if not "NumberOfEndPointType" in config:
            config["NumberOfEndPointType"] = 2
        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)

    
    try:
    
        endpointCount = int(config["NumberOfEndPointType"])

        shareList = config["Shares"].strip("()").split(',')
        shareCount = len(shareList)
        
        resourceList = config["ExecutionEnvironments"].strip("()").split(',')
        resourceCount = len(resourceList)
        
    except Exception, ex:
        sys.stderr.write(str(ex) + '\n')
        sys.exit(1)
    
    srvTable = {}
    srvTable[config['ComputingServiceId']] = {
        'type' : 'org.glite.ce.CREAM',
        'capabilities' : ['executionmanagement.jobexecution']
    }
    if config['EMIES'] == 'yes':
        srvTable[config["ESComputingServiceId"]] = {
            'type' : 'org.ogf.emies',
            'capabilities' : ['executionmanagement.jobcreation',
                              'executionmanagement.jobdescription',
                              'executionmanagement.jobmanagement',
                              'data.access.stageindir.gridftp',
                              'data.access.stageoutdir.gridftp',
                              'data.transfer.cepull.gridftp',
                              'data.transfer.cepush.gridftp',
                              'information.monitoring',
                              'information.discovery',
                              'information.discovery.resource', 
                              'information.lookup.job',
                              'information.query.xpath1',
                              'security.delegation']
        }
    
    out = sys.stdout
    
    for srvId in srvTable:
        srvDefs = srvTable[srvId]
        out.write("dn: GLUE2ServiceID=%s,GLUE2GroupID=resource,o=glue\n" % srvId)
        out.write("objectClass: GLUE2Entity\n")
        out.write("objectClass: GLUE2Service\n")
        out.write("objectClass: GLUE2ComputingService\n")
        
        out.write("GLUE2EntityCreationTime: %s\n" % now)
        out.write("GLUE2EntityName: Computing Service %s\n" % srvId)
        out.write("GLUE2EntityOtherInfo: InfoProviderName=glite-ce-glue2-computingservice-static\n")
        out.write("GLUE2EntityOtherInfo: InfoProviderVersion=%s\n" % infoprovVersion)
        out.write("GLUE2EntityOtherInfo: InfoProviderHost=%s\n" % hostname)
        
        out.write("GLUE2ServiceID: %s\n" % srvId)
        out.write("GLUE2ServiceType: %s\n" % srvDefs['type'])
        for capaItem in srvDefs['capabilities']:
            out.write("GLUE2ServiceCapability: %s\n" % capaItem)
        out.write("GLUE2ServiceQualityLevel: production\n")
        out.write("GLUE2ServiceComplexity: endpointType=%d, share=%d, resource=%d\n"
                   % (endpointCount, shareCount, resourceCount))
        out.write("GLUE2ServiceAdminDomainForeignKey: %s\n" % config['SiteId'])
        out.write("\n")



if __name__ == "__main__":
    main()

