#!/bin/sh

# This is a simple wrapper around globus-url-copy to perform a directory copy
# using tar streamed via gridftp.
#
# See http://www.mcs.anl.gov/~bresnaha/Stretch/ for other interesting ways
# to use this feature with any application that pipes data.
#
# In order to work with this feature, a server needs to be configured to
# enable the popen driver and tar with the following configuration options:
# -fs-whitelist file,popen,ordering -popen-whitelist tar:/bin/tar


## path or alias for gnu tar
LOCAL_TAR=tar
SERVER_TAR=tar

## parse the source and dest args
if [ "X$1" = "X" -o "X$2" = "X" ]; then
  echo "Usage: globus-dir-copy [source URL or path] [destination URL or path]"
  exit 1
fi

SRC_URL=${1%/}
SRC_PATH=${SRC_URL#*://*/}
if [ "${SRC_PATH}" != "${SRC_URL}" ]; then SRC_PATH=/$SRC_PATH; fi
SRC_TARGET=${SRC_PATH##*/}
SRC_PATH=${SRC_PATH%/*}
if [ "${SRC_PATH}X" = "X" ]; then SRC_PATH=.; fi

DEST_URL=${2%/}
DEST_PATH=${DEST_URL#*://*/}
if [ "${DEST_PATH}" != "${DEST_URL}" ]; then DEST_PATH=/$DEST_PATH; fi
if [ "${DEST_PATH}X" = "X" ]; then DEST_PATH=.; fi



## find transfer mode: get, put, third paty, or local.
case "$SRC_URL" in
  gsiftp://*|ftp://*)
    case "$DEST_URL" in
      gsiftp://*|ftp://*)
        MODE=tp
        ;;
      *)
        MODE=get
        ;;
    esac
    ;;
  *)
    case "$DEST_URL" in
      gsiftp://*|ftp://*)
        MODE=put
        ;;
      *)
        MODE=local
        ;;
    esac
    ;;
esac

#
# The path in the url doesn't affect the transfer, but include the full path
# so directory creation (-cd) will remain functional, and add TARSTREAM so 
# server logs will reflect what is going on.
#

case "$MODE" in
#####################################################################
  get)
#####################################################################
test -d "$DEST_PATH" || mkdir -p "$DEST_PATH" 2>/dev/null
globus-url-copy ${3} ${4} ${5} -src-pipe "${SERVER_TAR} cf - -C ${SRC_PATH} ${SRC_TARGET}" ${SRC_URL}/TARSTREAM - | ${LOCAL_TAR} xf - -C ${DEST_PATH}

;;
#####################################################################
  put)
#####################################################################

${LOCAL_TAR} cf - -C ${SRC_PATH} ${SRC_TARGET} | globus-url-copy -cd ${3} ${4} ${5} -dst-pipe "${SERVER_TAR} xf - -C ${DEST_PATH}" - ${DEST_URL}/TARSTREAM

;;
#####################################################################
  tp)
#####################################################################

globus-url-copy -cd ${3} ${4} ${5} -src-pipe "${SERVER_TAR} cf - -C ${SRC_PATH} ${SRC_TARGET}" -dst-pipe "${SERVER_TAR} xf - -C ${DEST_PATH}" ${SRC_URL}/TARSTREAM ${DEST_URL}/TARSTREAM

;;
#####################################################################
  local)
#####################################################################

test -d "$DEST_PATH" || mkdir -p "$DEST_PATH" 2>/dev/null
${LOCAL_TAR} cf - -C ${SRC_PATH} ${SRC_TARGET} | ${LOCAL_TAR} xf - -C ${DEST_PATH}

;;
esac

