#!/bin/sh

# Assume that we are called with a clean environment that cannot have
# been manipulated by the job.

# The job environment should have been saved in
# ${_CONDOR_SCRATCH_DIR}/parrot_job_env.sh

# load GLIDEIN_PARROT_OPTIONS and PARROT_CVMFS_REPO
GLIDEIN_PARROT_OPTIONS="-p $http_proxy"
GlideinUseParrotIDBox="false"
export PARROT_ALLOW_SWITCHING_CVMFS_REPOSITORIES=1

# If possible (i.e. not using glexec), share the tmp area between
# jobs that run in this slot.
# Also avoid using a shared area if this is an ssh_to_job session or
# any other hook that may run at the same time as the job.

parrot_tmp=${GLIDEIN_PARROT_TMP}
if [ -z "$parrot_tmp" ]; then
    parrot_tmp="${GLIDEIN_PARROT}/tmp${_CONDOR_SLOT}"
fi
if ! mkdir -p "$parrot_tmp" >& /dev/null || ! [ -w "$parrot_tmp" ] || ! [ -z "$_CONDOR_JOB_PIDS" ]; then
    parrot_tmp="${_CONDOR_SCRATCH_DIR}/parrot_tmp.$$"
fi

# map /tmp to a sub-directory of condor scratch directory
mkdir -p "${_CONDOR_SCRATCH_DIR}/tmp"
GLIDEIN_PARROT_OPTIONS="$GLIDEIN_PARROT_OPTIONS -M /tmp=${_CONDOR_SCRATCH_DIR}/tmp"

# If scratch dir is in /tmp/blah/..., then we must map /tmp/blah to itself
# to prevent the /tmp mapping from preventing access to scratch dir iself.
cscratch="${_CONDOR_SCRATCH_DIR}"
while [ "$cscratch" != "" ]; do
    parent=${cscratch%/*}
    if [ "$parent" = "$cscratch" ]; then
        break
    fi
    if [ "$parent" = "/tmp" ]; then
        GLIDEIN_PARROT_OPTIONS="$GLIDEIN_PARROT_OPTIONS -M ${cscratch}=${cscratch}"
    fi
    cscratch="$parent"
done

if [ "$GlideinUseParrotIDBox" != "false" ]; then

    # Make /dev/null writeable within the idbox.  We do this by mapping
    # /dev/null to a symlink to /dev/null, where the symlink exists in a
    # directory writeable by the idbox user.
    ln -f -s /dev/null ${_CONDOR_SCRATCH_DIR}/parrot_dev_null
    GLIDEIN_PARROT_OPTIONS="$GLIDEIN_PARROT_OPTIONS -M /dev/null=${_CONDOR_SCRATCH_DIR}/parrot_dev_null"

    # idbox_user name must not match name used in any other .__acl
    # files that are readable by parrot.
    idbox_user="glidusr$$"
    GLIDEIN_PARROT_OPTIONS="$GLIDEIN_PARROT_OPTIONS -H -u $idbox_user"

    # make scratch dir and sub-directories writeable within idbox
    find "${_CONDOR_SCRATCH_DIR}" -type d | while read dir; do
      echo "$idbox_user rwlx" > $dir/.__acl
    done
fi

export PARROT_HELPER="${GLIDEIN_PARROT}/libparrot_helper.so"

exec "${GLIDEIN_PARROT}/parrot_run" -t "$parrot_tmp" $GLIDEIN_PARROT_OPTIONS -- ${GLIDEIN_PARROT}/exec_job.sh "$@"

