#!/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-executionenvironment-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',
                      'ExecutionEnvironments']:
            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
    
    resList = config['ExecutionEnvironments'].strip("()").split(',')

    srvList = [config['ComputingServiceId']]
    if config['EMIES'] == 'yes':
        srvList.append(config['ESComputingServiceId'])
    
    
    for srvId in srvList:
    
        for tmpres in resList:
            
            resId = tmpres.strip()
            
            resKeys = ["ExecutionEnvironment_%s_SmpSize" % resId,
                       "ExecutionEnvironment_%s_Cores" % resId,
                       "ExecutionEnvironment_%s_ArchitecturePlatformType" % resId,
                       "ExecutionEnvironment_%s_LogicalCPUs" % resId,
                       "ExecutionEnvironment_%s_PhysicalCPUs" % resId,
                       "ExecutionEnvironment_%s_ProcessorVendor" % resId,
                       "ExecutionEnvironment_%s_ProcessorModel" % resId,
                       "ExecutionEnvironment_%s_ProcessorClockSpeed" % resId,
                       "ExecutionEnvironment_%s_MainMemoryRAMSize" % resId,
                       "ExecutionEnvironment_%s_MainMemoryVirtualSize" % resId,
                       "ExecutionEnvironment_%s_OperatingSystemFamily" % resId,
                       "ExecutionEnvironment_%s_OperatingSystemName" % resId,
                       "ExecutionEnvironment_%s_OperatingSystemRelease" % resId,
                       "ExecutionEnvironment_%s_NetworkAdapterInboundIP" % resId,
                       "ExecutionEnvironment_%s_NetworkAdapterOutboundIP" % resId]
            
            for keyX in resKeys:
                if not keyX in config:
                    sys.stderr.write("Missing definition for " + keyX  + '\n')
                    sys.exit(1)
            
            try:
            
                smpSize = int(config[resKeys[0]])
                cores = float(config[resKeys[1]])
                platform = config[resKeys[2]]
                lCPUs = int(config[resKeys[3]])
                pCPUs = int(config[resKeys[4]])
                if smpSize > 0:
                    totalInstances = lCPUs/smpSize
                else:
                    totalInstances = 0
                
                if lCPUs == pCPUs:
                    cpuType = 'single'
                else:
                    cpuType = 'multi'
                    
                if smpSize == (lCPUs/pCPUs):
                    coreType = 'single'
                else:
                    coreType = 'multi'
                    
                pVendor = config[resKeys[5]]
                pModel = config[resKeys[6]]
                pSpeed = config[resKeys[7]]
                memSize = int(config[resKeys[8]])
                virtSize = int(config[resKeys[9]])
                osType = config[resKeys[10]]
                osName = config[resKeys[11]]
                osVers = config[resKeys[12]]
                inConn = config[resKeys[13]].upper()
                outConn = config[resKeys[14]].upper()
                
            except Exception, ex:
                sys.stderr.write(str(ex) + '\n')
                sys.exit(1)

            out.write("dn: GLUE2ResourceID=%s,GLUE2ServiceID=%s,GLUE2GroupID=resource,o=glue\n"
                      % (resId, srvId))
            out.write("objectClass: GLUE2Entity\n")
            out.write("objectClass: GLUE2Resource\n")
            out.write("objectClass: GLUE2ExecutionEnvironment\n")
            out.write("GLUE2EntityCreationTime: %s\n" % now)
            out.write("GLUE2EntityName: %s\n" % resId)
            out.write("GLUE2EntityOtherInfo: InfoProviderName=glite-ce-glue2-executionenvironment-static\n")
            out.write("GLUE2EntityOtherInfo: InfoProviderVersion=%s\n" % infoprovVersion)
            out.write("GLUE2EntityOtherInfo: InfoProviderHost=%s\n" % hostname)
            out.write("GLUE2EntityOtherInfo: SmpSize=%d\n" % smpSize)
            out.write("GLUE2EntityOtherInfo: Cores=%f\n" % cores)

            out.write("GLUE2ResourceID: %s\n" % resId)
            out.write("GLUE2ResourceManagerForeignKey: %s_Manager\n" % srvId)

            out.write("GLUE2ExecutionEnvironmentPlatform: %s\n" % platform)
            out.write("GLUE2ExecutionEnvironmentTotalInstances: %d\n" % totalInstances)
            out.write("GLUE2ExecutionEnvironmentPhysicalCPUs: %d\n" % pCPUs)
            out.write("GLUE2ExecutionEnvironmentLogicalCPUs: %d\n" % lCPUs)
            out.write("GLUE2ExecutionEnvironmentCPUMultiplicity: %scpu-%score\n" 
                      % (cpuType, coreType))
            out.write("GLUE2ExecutionEnvironmentCPUVendor: %s\n" % pVendor)
            out.write("GLUE2ExecutionEnvironmentCPUModel: %s\n" % pModel)
            out.write("GLUE2ExecutionEnvironmentCPUClockSpeed: %s\n" % pSpeed)
            out.write("GLUE2ExecutionEnvironmentMainMemorySize: %d\n" % memSize)
            out.write("GLUE2ExecutionEnvironmentVirtualMemorySize: %d\n" % virtSize)
            out.write("GLUE2ExecutionEnvironmentOSFamily: %s\n" % osType)
            out.write("GLUE2ExecutionEnvironmentOSName: %s\n" % osName)
            out.write("GLUE2ExecutionEnvironmentOSVersion: %s\n" % osVers)
            out.write("GLUE2ExecutionEnvironmentConnectivityIn: %s\n" % inConn)
            out.write("GLUE2ExecutionEnvironmentConnectivityOut: %s\n" % outConn)
            out.write("GLUE2ExecutionEnvironmentComputingManagerForeignKey: %s_Manager\n" % srvId)
            out.write("\n")    


if __name__ == "__main__":
    main()

