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

def readTagsFromLDIF(scTable, ldiffilename):

    scRegex = re.compile('^\s*dn:\s+GlueSubClusterUniqueID=([^,]+),')
    asrRegex = re.compile('^\s*GlueHostApplicationSoftwareRunTimeEnvironment:\s+([^$]+)$')
    ldiffile = None
    
    try:
        ldiffile = open(ldiffilename)
        
        currSC = None
        for line in ldiffile:
            parsed = scRegex.match(line)
            if parsed:
                currSC = parsed.group(1).strip()
                scTable[currSC] = []
                continue
            
            parsed = asrRegex.match(line)
            if parsed and currSC:
                scTable[currSC].append(parsed.group(1).strip())
        
    finally:
        if ldiffile:
            ldiffile.close()

def readTagsFromFile(topDir):

    #
    # TODO see https://savannah.cern.ch/bugs/?96306
    #
    result = []
    if not os.path.isdir(topDir):
        return result
    
    for subItem in os.listdir(topDir):
        subDir = topDir + '/' + subItem
        tagfilename = '%s/%s.list' % (subDir, subItem)
        if not os.path.isdir(subDir) or not os.path.isfile(tagfilename):
                continue
        
        tagfile = None
        try:
            tagfile = open(tagfilename)
            for line in tagfile:
                tmps = line.strip()
                if len(tmps) == 0 or tmps.startswith('#'):
                    continue
                result = result + tmps.split()
        finally:
            if tagfile:
                tagfile.close()

    return result

def readTagsFromDir(scTable):

    globalTags = readTagsFromFile("/opt/edg/var/info")

    for scId in scTable:
        localTags = readTagsFromFile("/opt/glite/var/info/" + scId)
        scTable[scId] = scTable[scId] + (globalTags + localTags)


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())
    # Hardwire the data validity period to 1 hour for now
    validity = 3600
    
    conffile = None
    foundErr = False
    try:
        if len(sys.argv) <> 3:
            raise Exception("Usage: glite-ce-glue2-applicationenvironment-dynamic <config-file> <glue1 static cluster ldif 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])
    
        if not 'ComputingServiceId' in config:
            raise Exception("Missing attribute ComputingServiceId")
        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

    scTable = {}
    
    try:

        readTagsFromLDIF(scTable, sys.argv[2])

        readTagsFromDir(scTable)

    except Exception, ex:
        sys.stderr.write(str(ex) + '\n')
        sys.exit(1)

    srvList = [config['ComputingServiceId']]
    if config['EMIES'] == 'yes':
        srvList.append(config['ESComputingServiceId'])

    for srvId in srvList:
        
        for scId in scTable:
        
            for tag in scTable[scId]:
        
                out.write("dn: GLUE2ApplicationEnvironmentId=%s_%s,GLUE2ResourceId=%s,GLUE2ServiceID=%s,GLUE2GroupID=resource,o=glue\n"
                          % (tag, scId, scId, srvId))
                out.write("objectClass: GLUE2Entity\n")
                out.write("objectClass: GLUE2ApplicationEnvironment\n")
                out.write("GLUE2EntityCreationTime: %s\n" % now)
                out.write("GLUE2EntityValidity: %d\n" % validity)
                out.write("GLUE2ApplicationEnvironmentID: %s_%s\n" % (tag, scId))
                out.write("GLUE2EntityOtherInfo: InfoProviderName=glite-ce-glue2-applicationenvironment-dynamic\n")
                out.write("GLUE2EntityOtherInfo: InfoProviderVersion=%s\n" % infoprovVersion)
                out.write("GLUE2EntityOtherInfo: InfoProviderHost=%s\n" % hostname)
                out.write("GLUE2ApplicationEnvironmentAppName: %s\n" % tag)
                out.write("GLUE2ApplicationEnvironmentComputingManagerForeignKey: %s_Manager\n" % srvId)
                out.write("\n")


if __name__ == "__main__":
    main()

