#!/bin/sh

DownloadFile() {
  src=$1
  dest="file://$2"
  source $OSG_GRID/setup.sh
  tries=1
  debug=""
  while ! globus-url-copy $debug $src $dest >&2; do
    # the problem may be that the grid-proxy has expired
    if which grid-proxy-info >& /dev/null; then
      if ! grid-proxy-info -exists; then
        echo "OSG site job wrapper ABORTING job at `date` on host `hostname -f`, because grid-proxy is not valid, so download of executable cannot succeed." >&2
        return 127
      fi
    fi

    echo "OSG site job wrapper failed to download $src at `date` on host `hostname -f` (try $tries/10)." >&2

    debug="-dbg -vb"
    tries=$(($tries+1))
    if [ $tries -gt 10 ]; then
      return 1
    fi
    sleep $((10+$tries*2))
  done
  return 0
}

ExitAndRequeue() {
  # The job should use OnExitRemove to requeue the job if it exits with SIGUSR1
  kill -USR1 $$
}

if [ "$OSG_JOB_WRAPPER_CMD" = "" ]; then
  #There is no CMD specified to exec, so we should download one.
  if [ "$OSG_JOB_WRAPPER_CMD_URL" = "" ]; then
    echo "OSG site job wrapper found no OSG_JOB_WRAPPER_CMS_URL defined in environment." >&2
    exit 127
  fi

  if ! [ -d "$OSG_GRID" ]; then
    echo "OSG site job wrapper found no OSG_GRID directory: $OSG_GRID" >&2
    ExitAndRequeue
  fi

  # Setting the timestamp back (below) is not sufficient to prevent
  # condor from thinking the downloaded executable file is an output
  # file, so put it in a sub-directory.  Condor does not (currently)
  # transfer back any files in sub-directories.
  mkdir "$_CONDOR_SCRATCH_DIR/_osg_wrapper"
  OSG_JOB_WRAPPER_CMD="$_CONDOR_SCRATCH_DIR/_osg_wrapper/_osg_wrapper_exec"
  DownloadFile "$OSG_JOB_WRAPPER_CMD_URL" "$OSG_JOB_WRAPPER_CMD"
  rc=$?
  if [ $rc != 0 ]; then
    echo "OSG site job wrapper failed to download "$OSG_JOB_WRAPPER_CMD_URL" to $OSG_JOB_WRAPPER_CMD" >&2
    [ $rc = 127 ] && exit 127
    ExitAndRequeue
  fi
  #Move timestamp back so condor doesn't think this is an output file
  #Since -B option is not portable, just hard-code the timestamp
  #touch -B 3600 "$OSG_JOB_WRAPPER_CMD"
  touch -t 200001010101.00 "$OSG_JOB_WRAPPER_CMD"
  chmod u+x "$OSG_JOB_WRAPPER_CMD"
fi

if [ "$OSG_JOB_WRAPPER_CMD" = "" ]; then
  echo "OSG site job wrapper found no OSG_JOB_WRAPPER_CMD defined in environment." >&2
  exit 127
fi

if [ -x "$_CONDOR_SCRATCH_DIR/$OSG_JOB_WRAPPER_CMD" ]; then
  OSG_JOB_WRAPPER_CMD="$_CONDOR_SCRATCH_DIR/$OSG_JOB_WRAPPER_CMD"
fi

if [ "$_CONDOR_SCRATCH_DIR" != "" ]; then
  export OSG_WN_TMP=$_CONDOR_SCRATCH_DIR
  export EDG_WL_SCRATCH=$_CONDOR_SCRATCH_DIR
  export GRID3_TMP_WN_DIR=$_CONDOR_SCRATCH_DIR
  export TMPDIR=$_CONDOR_SCRATCH_DIR
fi

exec $OSG_JOB_WRAPPER_CMD "$@"
