# Path: pUtil.py
# def tolog(msg, tofile=True, label='INFO', essential=False):
#     """ Write date+msg to pilot log and to stdout """
# 
#     try:
#         import inspect
# 
#         MAXLENGTH = 12
#         # getting the name of the module that is invoking tolog() and adjust the length
#         try:
#             module_name = os.path.basename(inspect.stack()[1][1])
#         except Exception, e:
#             module_name = "unknown"
#             #print "Exception caught by tolog(): ", e,
#         module_name_cut = module_name[0:MAXLENGTH].ljust(MAXLENGTH)
#         msg = "%i|%s| %s" % (os.getpid(),module_name_cut, msg)
# 
#         t = timeStampUTC(format='%Y-%m-%d %H:%M:%S')
#         if tofile:
#             appendToLog("%s|%s\n" % (t, msg))
# 
#         # remove backquotes from the msg since they cause problems with batch submission of pilot
#         # (might be present in error messages from the OS)
#         msg = msg.replace("`","'")
#         msg = msg.replace('"','\\"')
#         print "%s| %s" % (t, msg)
# 
#         # write any FAILED messages to stderr
#         if "!!FAILED!!" in msg:
#             try:
#                 print >> sys.stderr, "%s| %s" % (t, msg)
#             except:
#                 print "Failed to print to sys.stderr: %s" % (t, msg)
#     except:
#         print "!!WARNING!!4000!! %s" % traceback.format_exc()
# 
# def readpar(parameter, alt=False, version=0, queuename=None):
#     """ Read 'parameter' from queuedata via SiteInformation class """
# 
#     from SiteInformation import SiteInformation
#     si = SiteInformation()
# 
#     return si.readpar(parameter, alt=alt, version=version, queuename=queuename)
# 
# def getExperiment(experiment):
#     """ Return a reference to an experiment class """
# 
#     from ExperimentFactory import ExperimentFactory
#     factory = ExperimentFactory()
#     _exp = None
# 
#     try:
#         experimentClass = factory.newExperiment(experiment)
#     except Exception, e:
#         tolog("!!WARNING!!1114!! Experiment factory threw an exception: %s" % (e))
#     else:
#         _exp = experimentClass()
# 
#     return _exp


import re
import os
from pUtil import tolog, readpar, getExperiment

    return container_name

def singularityWrapper(cmd, platform, workdir, experiment="ATLAS"):
    """ Prepend the given command with the singularity execution command """
    # E.g. cmd = /bin/bash hello_world.sh
    # -> singularity_command = singularity exec -B <bindmountsfromcatchall> <img> /bin/bash hello_world.sh
    # singularity exec -B <bindmountsfromcatchall>  /cvmfs/atlas.cern.ch/repo/images/singularity/x86_64-slc6.img <script> 

    # Should a container be used?
    container_name = getContainerName()
    if container_name == 'singularity':
        tolog("Singularity has been requested")

        # Get the singularity options
        singularity_options = extractSingularityOptions()
        if singularity_options != "":
            # Get the image path
            image_path = getGridImageForSingularity(platform, experiment)

            # Does the image exist?
            if os.path.exists(image_path):
                # Prepend it to the given command
                cmd = "export workdir=" + workdir + "; singularity exec " + singularity_options + " " + image_path + " /bin/bash -c \'cd $workdir;pwd;" + cmd.replace("\'","\\'").replace('\"','\\"') + "\'"
            else:
                tolog("!!WARNING!!4444!! Singularity options found but image does not exist: %s" % (image_path))
        else:
            # Return the original command as it was
            tolog("No singularity options found in container_options or catchall fields")


# Path: pUtil.py
# def tolog(msg, tofile=True, label='INFO', essential=False):
#     """ Write date+msg to pilot log and to stdout """
# 
#     try:
#         import inspect
# 
#         MAXLENGTH = 12
#         # getting the name of the module that is invoking tolog() and adjust the length
#         try:
#             module_name = os.path.basename(inspect.stack()[1][1])
#         except Exception, e:
#             module_name = "unknown"
#             #print "Exception caught by tolog(): ", e,
#         module_name_cut = module_name[0:MAXLENGTH].ljust(MAXLENGTH)
#         msg = "%i|%s| %s" % (os.getpid(),module_name_cut, msg)
# 
#         t = timeStampUTC(format='%Y-%m-%d %H:%M:%S')
#         if tofile:
#             appendToLog("%s|%s\n" % (t, msg))
# 
#         # remove backquotes from the msg since they cause problems with batch submission of pilot
#         # (might be present in error messages from the OS)
#         msg = msg.replace("`","'")
#         msg = msg.replace('"','\\"')
#         print "%s| %s" % (t, msg)
# 
#         # write any FAILED messages to stderr
#         if "!!FAILED!!" in msg:
#             try:
#                 print >> sys.stderr, "%s| %s" % (t, msg)
#             except:
#                 print "Failed to print to sys.stderr: %s" % (t, msg)
#     except:
#         print "!!WARNING!!4000!! %s" % traceback.format_exc()
# 
# def readpar(parameter, alt=False, version=0, queuename=None):
#     """ Read 'parameter' from queuedata via SiteInformation class """
# 
#     from SiteInformation import SiteInformation
#     si = SiteInformation()
# 
#     return si.readpar(parameter, alt=alt, version=version, queuename=queuename)
# 
# def getExperiment(experiment):
#     """ Return a reference to an experiment class """
# 
#     from ExperimentFactory import ExperimentFactory
#     factory = ExperimentFactory()
#     _exp = None
# 
#     try:
#         experimentClass = factory.newExperiment(experiment)
#     except Exception, e:
#         tolog("!!WARNING!!1114!! Experiment factory threw an exception: %s" % (e))
#     else:
#         _exp = experimentClass()
# 
#     return _exp


# Path: Singularity.py
import re
import os
from pUtil import tolog, readpar, getExperiment


    return container_name

def singularityWrapper(cmd, platform, workdir, experiment="ATLAS"):
    """ Prepend the given command with the singularity execution command """
    # E.g. cmd = /bin/bash hello_world.sh
    # -> singularity_command = singularity exec -B <bindmountsfromcatchall> <img> /bin/bash hello_world.sh
    # singularity exec -B <bindmountsfromcatchall>  /cvmfs/atlas.cern.ch/repo/images/singularity/x86_64-slc6.img <script> 

    # Should a container be used?
    container_name = getContainerName()
    if container_name == 'singularity':
        tolog("Singularity has been requested")

        # Get the singularity options
        singularity_options = extractSingularityOptions()
        if singularity_options != "":
            # Get the image path
            image_path = getGridImageForSingularity(platform, experiment)

            # Does the image exist?
            if os.path.exists(image_path):
                # Prepend it to the given command
                cmd = "export workdir=" + workdir + "; singularity exec " + singularity_options + " " + image_path + " /bin/bash -c \'cd $workdir;pwd;" + cmd.replace("\'","\\'").replace('\"','\\"') + "\'"
            else:
                tolog("!!WARNING!!4444!! Singularity options found but image does not exist: %s" % (image_path))
        else:
            # Return the original command as it was
            tolog("No singularity options found in container_options or catchall fields")


    tolog("Using command %s" % cmd)