#!/bin/sh

# Input args: <subreqid> <fileid> <physicalpath>
#
subreqID=$1
fileID=$2
physPath=$3
prepPath=/xroot/adm/OFS.events

# Common subroutines (set DEBUG variable to 1 for debugging)
#
DEBUG=1

Wait4File () {
    Debug "Checking file $2 ..."
    tcnt=18
    time=5
    warn=0
    until test -${1} $2 -o $tcnt -eq 0; do
          if [ $warn -eq 0 ]; then
             Debug "File $2 not found. Waiting $time seconds..."
          fi
          /bin/sleep $time
          tcnt=`/usr/bin/expr $tcnt - 1`
          warn=`/usr/bin/expr $warn + 1`
    done
    if [ $tcnt -le 0 ]; then
       Debug "File $2 not found after $warn tries; prepare assumed."
       echo $subreqID:$fileID prep $physPath >> $prepPath
       exit
    fi
    }

Debug () {
    if [ $DEBUG -eq 1 ]; then
       /bin/echo XrdCS2e: $1 >> /tmp/XrdCS2e.log
    fi
    }

# The rendezvous script is normally placed in '/xroot/db/pending' (though the
# default is /tmp/XrdCS2d). It has a name equal to the fileid. See the
# oss.stagecmd directive in the config file which specifies the default root 
# path as an argument to XrdCS2d. So, we will wait here for the file to be 
# created (but not for too long).
#
  base=/xroot/db/pending/
  Debug "XrdCS2e called: $0 $1 $2 $3"
  /bin/touch $physPath
  Wait4File r $base$fileID

# The file has the request filename (Rfn), the physical file name (Pfn),
# the logical file name (Lfn), and the event FIFO file name (Efn). Source
# the file to get these variables assigned.
#
  . $base$fileID

# The first order of business is record our subreqID in the request file
#
  echo $subreqID >> $Rfn

# The next step is to create the symlink to the physical file
#
  /bin/rm $Pfn
  /bin/ln -s $physPath $Pfn

# Now we need to tell xrootd that the file is available
#
  echo stage OK $Lfn >> $Efn

# We leave the pending file where it is because there may have been numerous
# requests made against this file (each will cause the script to be executed).
# The daemon will figure out when the file should be erased.
