#!/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"
RSYNC="/usr/bin/rsync"
enstorekt_path="/fnal/ups/kt/enstorekt"

if [ ! -x ${RSYNC} ]; then
    echo "no rsync found"
    exit 1
fi

do_rsync() {
    if [ "${ENSSH:-x}" != "x" ]; then
	${RSYNC} --rsh=${ENSSH} "$@"
    else
	if [ -d $krbdir ]; then
	    ${RSYNC} --rsh=${krbdir}/rsh "$@"
	else
	    ${RSYNC} "$@"
	fi
    fi
    rc=$?
    return $rc
}

# 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


   OLDKRB5CCNAME=${KRB5CCNAME:-NONE}
   if [ "$user" = "root" ]; then
      # the user is root
      KRB5CCNAME=/tmp/krb5cc_root_$$;export KRB5CCNAME
      ${krbdir}/kinit -k host/${thisHost}
      do_rsync "$@"
      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
      KRB5CCNAME=/tmp/krb5cc_enstore_$$;export KRB5CCNAME
      ${krbdir}/kinit -k -t $enstorekt_path enstore/cd/${thisHost}
      do_rsync "$@"
      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
      do_rsync "$@"
      rc=$?
      # only destroy the ticket if we obtained one using kcron
      if [ "$OLDKRB5CCNAME" != "" ]; then ${krbdir}/kdestroy; fi;
   fi
else
   # we are not kerberized
   rc=do_rsync "$@"
fi

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