#!/bin/sh
set -u
debug=0

# do an rcp.  if this returns an error, try an scp.
do_rcp () {
   cmd=$1
   shift
   $cmd $@ 2> /dev/null 
   rc=$?
   if [ "$rc" == "1" ]; then
      # there was an error, maybe rcp support is turned off
      scp -c blowfish $@ 
      rc=$?
   fi
   return $rc
}

if [ "${1:-}" = "-x" ] ; 
then 
    set -xv
    shift
    debug=1
fi

# process inputs
if [ $# -lt 2 ]; then
   # we need at least 2 arguments
   if [ $debug -eq 1 ]; then set +xv; fi
   exit 1
fi

# constants
krbdir="/usr/krb5/bin"
defaultDomain=".fnal.gov"
enstorekt_path="/fnal/ups/kt/enstorekt"

# if we are a kerberized system, we need to do some pre rcp stuff
# for the root user. if not, just do a normal rcp

if [ -d $krbdir -a -f $enstorekt_path ]; then
   # we are kerberized

   # get some values
   user=`whoami`
   host=`uname -n`

   # we need the full domain name, if no domain is there, add default one on
   if expr $host : '.*\.' >/dev/null;then 
      thisHost=$host;
   else 
      thisHost=${host}${defaultDomain};
   fi

   if [ "$user" = "root" ]; then
      # the user is root
      OLDKRB5CCNAME=${KRB5CCNAME:-NONE}
      KRB5CCNAME=/tmp/krb5cc_root_$$;export KRB5CCNAME
      ${krbdir}/kinit -k host/${thisHost}
      if [ "${ENSCP:-x}" != "x" ];then
	rc=do_rcp $ENSCP "$@"
      else
	do_rcp $krbdir/rcp "$@"
      fi
      rc=$?
      ${krbdir}/kdestroy
      # if we had an old ticket cache, restore it
      if [ $OLDKRB5CCNAME != "NONE" ]; then KRB5CCNAME=$OLDKRB5CCNAME; fi

   elif [ "$user" = "enstore" ]; then
      # the user is enstore
      OLDKRB5CCNAME=${KRB5CCNAME:-NONE}
      KRB5CCNAME=/tmp/krb5cc_enstore_$$;export KRB5CCNAME
      ${krbdir}/kinit -k -t $enstorekt_path enstore/cd/${thisHost}
      if [ "${ENSCP:-x}" != "x" ];then
	rc=do_rcp $ENSCP "$@"
      else
	do_rcp $krbdir/rcp "$@"
      fi
      rc=$?
      ${krbdir}/kdestroy
      # if we had an old ticket cache, restore it
      if [ $OLDKRB5CCNAME != "NONE" ]; then KRB5CCNAME=$OLDKRB5CCNAME; fi

   else
      # this is someone else, see if we have a ticket before doing anything
      OLDKRB5CCNAME=""
      ${krbdir}/klist -s
      if [ $? -eq 1 ];
      then
        # no we do not, try to get one using kcron
	OLDKRB5CCNAME="YES"
	KRB5CCNAME=/tmp/krb5cc_myjob_$$;export KRB5CCNAME
	${krbdir}/kcron 2> /dev/null
      fi
      if [ "${ENSCP:-x}" != "x" ];then
	rc=do_rcp $ENSCP "$@"
      else
	do_rcp $krbdir/rcp "$@"
      fi
      rc=$?
      # only destroy the ticket if we obtained one using kcron
      if [ "$OLDKRB5CCNAME" != "" ]; then ${krbdir}/kdestroy; fi;
   fi

else
   # we are not kerberized
    if [ "${ENSCP:-x}" != "x" ];then
	do_rcp $ENSCP "$@" 
   else
	do_rcp rcp "$@"
	rc=$?
   fi
fi

if [ $debug -eq 1 ]; then set +xv; fi
exit $rc
