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

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"

set +u
if [ -n "$ENSCP" ];then
    /usr/bin/rsync --rsh=$ENSCP "$@"
    exit $?
fi
set -u

# 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 ]; 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}
      /usr/bin/rsync --rsh=${krbdir}/rsh "$@"
      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 /local/ups/kt/enstorekt enstore/cd/${thisHost}
      /usr/bin/rsync --rsh=${krbdir}/rsh "$@"
      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
      /usr/bin/rsync --rsh=${krbdir}/rsh "$@"
      rc=$?
      # only destroy the ticket if we obtained one using kcron
      if [ "$OLDKRB5CCNAME" != "" ]; then ${krbdir}/kdestroy; fi;
   fi

else
   # we are not kerberized
    rsync "$@"
    rc=$?
fi

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