#!/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-share-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',
                      'Shares']:
            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
    
    shareList = config['Shares'].strip('()').split(',')

    #
    # We used regular expression to discriminate the kind of service
    # the endpoint must be in the form <host>_<interfacename>
    #
    srvTable = {}
    srvTable[config['ComputingServiceId']] = (re.compile('[^_]+_org\.glite\.ce\.CREAM'), True)
    if config['EMIES'] == 'yes':
        #
        # TODO select only meaningful port types
        #
        tmps = '(creation|activitymanagement|delegation|activityinfo|resourceinfo)'
        srvTable[config['ESComputingServiceId']] = (re.compile('[^_]+_org\.ogf\.emies\.%s' % tmps), False) 

    for srvId in srvTable:
    
        srvRe, isLegacy = srvTable[srvId]
        
        for shareItem in shareList:
        
            shareName = shareItem.strip()
            shareId = "%s_%s" % (shareName, srvId)
            
            shKeys = ["SHARE_%s_QUEUENAME" % shareName,
                      "SHARE_%s_OWNER" % shareName,
                      "SHARE_%s_CEIDS" % shareName,
                      "SHARE_%s_EXECUTIONENVIRONMENTS" % shareName,
                      "SHARE_%s_ENDPOINTS" % shareName,
                      "SHARE_%s_ACBRS" % shareName]
            
            for keyX in shKeys:
                if not keyX in config:
                    sys.stderr.write("Missing definition for " + keyX)
                    sys.exit(1)
                    
            qname = config[shKeys[0]]
            
            owner = config[shKeys[1]]
            
            ceIdList = config[shKeys[2]].strip('()').split(',')
                        
            envList = config[shKeys[3]].strip('()').split(',')
            
            epList = []
            for tmpId in config[shKeys[4]].strip('()').split(','):
                if srvRe.match(tmpId):
                    epList.append(tmpId)
            
            acbrList = config[shKeys[5]].strip('()').split(',')
            
            
            out.write("dn: GLUE2ShareID=%s,GLUE2ServiceID=%s,GLUE2GroupID=resource,o=glue\n" 
                      % (shareId, srvId))
            out.write("objectClass: GLUE2Entity\n")
            out.write("objectClass: GLUE2Share\n")
            out.write("objectClass: GLUE2ComputingShare\n")
            out.write("GLUE2EntityCreationTime: %s\n" % now)
            if isLegacy:
                for ceId in ceIdList:
                    out.write("GLUE2EntityOtherInfo: CREAMCEId=%s\n" % ceId.strip())
                out.write("GLUE2EntityOtherInfo: ServiceType=org.glite.ce.CREAM\n")
            else:
                out.write("GLUE2EntityOtherInfo: ServiceType=org.ogf.emies\n")
            out.write("GLUE2EntityOtherInfo: InfoProviderName=glite-ce-glue2-share-static\n")
            out.write("GLUE2EntityOtherInfo: InfoProviderVersion=%s\n" % infoprovVersion)
            out.write("GLUE2EntityOtherInfo: InfoProviderHost=%s\n" % hostname)
            
            out.write("GLUE2ShareID: %s\n" % (shareId))
            out.write("GLUE2ShareDescription: Share of %s for %s\n" % (qname, owner))
            if len(envList) > 0:
                out.write("GLUE2ShareResourceForeignKey: %s\n" % envList[0].strip())
            for epItem in epList:
                out.write("GLUE2ShareEndpointForeignKey: %s\n" % epItem.strip())
            out.write("GLUE2ShareServiceForeignKey: %s\n" % srvId)

            out.write("GLUE2ComputingShareMappingQueue: %s\n" % qname)
            # Default value for Serving state is production
            # Real value supposed to be provided by the dynamic plugin
            out.write("GLUE2ComputingShareServingState: production\n")
            # Real values supposed to be provided by the dynamic plugin
            out.write("GLUE2ComputingShareDefaultCPUTime: 999999999\n")
            out.write("GLUE2ComputingShareMaxCPUTime: 999999999\n")
            out.write("GLUE2ComputingShareDefaultWallTime: 999999999\n")
            out.write("GLUE2ComputingShareMaxWallTime: 999999999\n")
            out.write("GLUE2ComputingShareMaxRunningJobs: 999999999\n")
            out.write("GLUE2ComputingShareRunningJobs: 0\n")
            out.write("GLUE2ComputingShareTotalJobs: 0\n")
            out.write("GLUE2ComputingShareFreeSlots: 0\n")
            out.write("GLUE2ComputingShareWaitingJobs: 444444\n")
            out.write("GLUE2ComputingShareEstimatedAverageWaitingTime: 2146660842\n")
            out.write("GLUE2ComputingShareEstimatedWorstWaitingTime: 2146660842\n")
            if len(envList) > 0:
                out.write("GLUE2ComputingShareExecutionEnvironmentForeignKey: %s\n" % envList[0].strip())
            for epItem in epList:
                out.write("GLUE2ComputingShareComputingEndpointForeignKey: %s\n" % epItem.strip())
            out.write("GLUE2ComputingShareComputingServiceForeignKey: %s\n" % srvId)
            out.write("\n")
            
            
            out.write("dn: GLUE2PolicyID=%s_policy,GLUE2ShareId=%s,GLUE2ServiceID=%s,GLUE2GroupID=resource,o=glue\n"
                      % (shareId, shareId, srvId))
            out.write("objectClass: GLUE2Entity\n")
            out.write("objectClass: GLUE2Policy\n")
            out.write("objectClass: GLUE2MappingPolicy\n")
            out.write("GLUE2EntityCreationTime: %s\n" % now)

            out.write("GLUE2PolicyID: %s_policy\n" % shareId)
            out.write("GLUE2PolicyScheme: org.glite.standard\n")
            for acbr in acbrList:
                out.write("GLUE2PolicyRule: %s\n" % acbr.strip())
            out.write("GLUE2PolicyUserDomainForeignKey: %s\n" % owner)

            out.write("GLUE2MappingPolicyShareForeignKey: %s\n" % shareId)
            out.write("\n")




if __name__ == "__main__":
    main()

