#!/bin/sh


printCanonicalPath() # in $1 = path                                                    
{                                                                                      
local link                                                                         
local ret                                                                          
link="$1"                                                                          
if readlink -f / > /dev/null 2>&1; then                                            
readlink -f "$link"                                                            
else                                                                               
ret="$(cd $(dirname "$link"); pwd -P)/$(basename "$link")"                     
while [ -h "$ret" ]; do                                                        
link="$(readlink "$ret")"                                                  
if [ -z "${link##/*}" ]; then                                              
ret="${link}"                                                          
else                                                                       
link="$(dirname $ret)/${link}"                                         
ret="$(cd $(dirname "$link"); pwd -P)/$(basename "$link")"             
fi                                                                         
done                                                                           
echo "$ret"                                                                    
fi                                                                                 
}                                                                                      

if [ -z "$SRM_PATH" ]; then                                                            
SRM_PATH="$(cd "$(dirname "$(printCanonicalPath "$0")")/../share/srm"; pwd -P)"    
fi                                                                                     

if [ ! -d "$SRM_PATH" ]; then                                                          
echo "${SRM_PATH} is not a directory"                                              
exit 2                                                                             
fi                                                                                     

export SRM_PATH                                                                        


args=$*

error() {
    echo "Can't copy from \"${1}\" protocol to \"${2}\"  protocol"
    exit 1
}

check_protocols() {
    case "$1" in
	gsiftp)
	    ;;
	enstore)
	    ;;
	dcap)
	    ;;
	file)
	    ;;
	*)
	    echo "Unsupported protocol: \"$1\""
	    exit 1
    esac
}

skip=0

##  haveSrm is a boolean variable that describes whether either of the
##  two transfer URLs involved in the transfer uses the 'srm' schema
##  (i.e., starts 'srm:').  A value of '0' indicates that neither URL
##  has the 'srm' schema; a value of '1' indicates that at least one
##  URL has the 'srm' schema.
haveSrm=0

##  delegationMakesSense is a boolean variable that describes whether
##  the user-supplied URLs suggest that delegation would be useful.  A
##  value of '0' indicates that delegation is not useful; a value of
##  '1' indicates that the transfer will likely require delegation.
delegationMakesSense=0

##  haveDelegate is a boolean variable that describes whether the user
##  has supplied the '-delegate' option.  A value of '0' indicates the
##  user is accepting the default value by not specifying the option;
##  a value of '1' indicates that the user specified the '-delegate'
##  option.
haveDelegate=0

i=0
fargs=

for arg in $args;
  do
  case "${arg}" in
      -help|-version|--help)
	  skip=1
	  continue
	  ;;
      -copyjobfile*)
	  hasThirdPartyTransfer=0
	  copyJobFile="${arg##-copyjobfile=}"
	  if [ -r "$copyJobFile" ]; then
	      hasThirdPartyTransfer=1
	      grep -E -e '^ *(srm|gsiftp|gridftp|https):[^ ]* (srm|gsiftp|gridftp|https):' "$copyJobFile" >/dev/null || hasThirdPartyTransfer=0
	  fi
	  if [ $hasThirdPartyTransfer -eq 1 ]; then
	      delegationMakesSense=1
	  fi
	  skip=1
	  continue
	  ;;
      srm:*)
          if [ "$haveSrm" = 0 ]; then
	      haveSrm=1
          else
              delegationMakesSense=1
          fi
	  skip=1
	  continue
	  ;;
      file:*|http:*)
	  skip=1
	  continue
	  ;;
      gsiftp:*|gridftp:*|https:*)
	  delegationMakesSense=1
	  skip=1
	  continue
	  ;;
      -delegate|-delegate=*)
          haveDelegate=1
          continue
          ;;
      *=*|-*)
	  continue
	  ;;
  esac
  fargs[i]=${arg}
  i=$((${i}+1))
done


#
# if any of the input args contain srm or help - fall through to standard java call
#

length=${#fargs[*]}
last=$((${length}-1))
first=${#fargs[0]}

cmd=""
if [ "${skip}" -eq 0 ]
    then
    if [ ${length} -lt 2 ]; then
	exec "${SRM_PATH}/lib/srm" -copy "$@"
    else
	i=0
	src_protocols=
	src_files=
	while [ $i -lt ${last} ]
	do
	  src_protocols[$i]=`echo ${fargs[$i]} | grep ":" | cut -d":" -f1`
	  i=$((${i}+1))
	done
	n_src_protocols=`echo  ${src_protocols[@]} | tr A-Z a-z | tr ' ' '\012' | sort | uniq | wc -l`
	if [  ${n_src_protocols} -ne 1 ]
	    then
	    echo "Wrong number of input protocols:  ${n_src_protocols}"
	    echo "    0 - check validity of URL spelling"
	    echo "   >1 - mixture of protocols is not supported "
	    exit 1
	else
	    src_protocol=${src_protocols[0]}
	    dst_protocol=`echo ${fargs[${last}]} | grep ":" | cut -d":" -f1`
	    check_protocols ${src_protocol}
	    check_protocols ${dst_protocol}
	    if [ "${src_protocol}" = "${dst_protocol}" ]
		then
		case "${src_protocol}" in
		    gsiftp)
			cmd="globus-url-copy ${fargs[*]}"
			;;
		    file)
			cmd="cp `echo ${fargs[*]} | sed -e "s/${src_protocol}://g"`"
			;;
		    *)
			error ${src_protocol}  ${dst_protocol}
		esac
	    else

		if [ "${src_protocol}" = "gsiftp" -o "${dst_protocol}" = "gsiftp" ]
		    then
		    cmd="globus-url-copy ${fargs[*]}"
		fi

		if [ "${src_protocol}" = "enstore" -o "${dst_protocol}" = "enstore" ]
		    then
		    cmd="encp `echo ${fargs[*]} | sed -e "s/${src_protocol}://g" | sed -e "s/${dst_protocol}://g"`"
		fi


		if [ "${src_protocol}" = "dcap" -o  "${dst_protocol}" = "dcap" ]
		    then
		    if [ "${src_protocol}" = "file" ]
			then
			cmd="dccp `echo ${fargs[*]:0:${last}} | sed -e "s/${src_protocol}://g"` ${fargs[*]:${last}}"
		    else
			cmd="dccp `echo ${fargs[*]:0:${last}}` `echo ${fargs[*]:${last}} | sed -e "s/${dst_protocol}://g"`"
		    fi
		fi

		#
		# all bad cases go here
		#

		if [ "${src_protocol}" = "gsiftp" -a "${dst_protocol}" = "enstore" ]
		    then
		    error ${src_protocol} ${dst_protocol}
		fi

		if [ "${dst_protocol}" = "gsiftp" -a "${src_protocol}" = "enstore" ]
		    then
		    error ${src_protocol} ${dst_protocol}
		fi


		if [ "${src_protocol}" = "dcap" -a "${dst_protocol}" = "gsiftp" ]
		    then
		    error ${src_protocol} ${dst_protocol}
		fi

		if [ "${dst_protocol}" = "dcap" -a "${src_protocol}" = "gsiftp" ]
		    then
		    error ${src_protocol} ${dst_protocol}
		fi

		if [ "${src_protocol}" = "dcap" -a "${dst_protocol}" = "enstore" ]
		    then
		    error ${src_protocol} ${dst_protocol}
		fi

		if [ "${dst_protocol}" = "dcap" -a "${src_protocol}" = "enstore" ]
		    then
		    error ${src_protocol} ${dst_protocol}
		fi
	    fi
	    exec $cmd
	fi
    fi
else
    if [ "$delegationMakesSense" = 1 ] && [ "$haveDelegate" = 0 ]; then
        delegate=-delegate=true
    fi
    exec "${SRM_PATH}/lib/srm" -copy $delegate "$@"
fi
