# description: executes the job inside singularity container
# param:SINGULARITY_IMAGE:string:NULL:singularity image or tree per VO, key:value comma separated, key default if VO not matched
# param:SINGULARITY_OPTIONS:string: :singularity options
# param:BINARY_PATH:string:/usr/bin/singularity:singularity binary location

SINGULARITY_OPTIONS="${SINGULARITY_OPTIONS:-}"
SINGULARITY_IMAGE="${SINGULARITY_IMAGE:-}"
BINARY_PATH="${BINARY_PATH:-'/usr/bin/singularity'}"
BINARY_PATH="${4:-$BINARY_PATH}"

DEFAULT_IMAGE="NULL"


if [ "x$1" = "x0" ]; then

    LOCAL_FILE=$(control_path "${joboption_controldir}" "${joboption_gridid}" "local")
    
    # get VO
    #vo=`arcproxy -P $joboption_controldir/job.$joboption_gridid.proxy -i vomsVO 2> /dev/null`
    vo=`grep voms= $LOCAL_FILE | awk -F / '{print $2}'|sort -u`
    
    values=`echo $SINGULARITY_IMAGE | sed -e 's/,/ /g'`
    for i in $values
    do
        voname=`echo $i | awk -F : '{print $1}'`
        voimage=`echo $i | awk -F : '{print $2}'`
	if [ "xdefault" = "x$voname" ]; then
	    DEFAULT_IMAGE=$voimage
	fi
	if [ "x$vo" = "x$voname" ] ; then
	    IMAGE=$voimage
	fi
    done

    IMAGE="${IMAGE:-$DEFAULT_IMAGE}"

    # explicit image, NULL skips container
    IMAGE="${2:-$IMAGE}"
    # unquote IMAGE
    temp="${IMAGE%\"}"
    temp="${temp#\"}"
    IMAGE=$temp

    # Check if singularity already used/set by another RTE
    echo $joboption_args |grep -q singularity; sused=$?

    if [ "x$IMAGE" != "xNULL" ] && [ "x$sused" == "x1" ] ; then
       joboption_args="$BINARY_PATH exec $SINGULARITY_OPTIONS --home \${RUNTIME_JOB_DIR} $IMAGE $joboption_args"
       # account singularity image usage
       export ACCOUNTING_WN_INSTANCE="${IMAGE}"
    fi
fi
