#!/bin/sh
set -u
if [ "${1:-}" = "-x" ] ; then set -xv; shift; fi

# process inputs
if [ $# -lt 2 ]; then
   # we need at least the node name and the rsh string
   set +xv
   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 rsh stuff.
# if not, just do a normal rsh


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 [ "${ENSSH:-x}" != "x" ];then
	$ENSSH "$@" 
      else
	${krbdir}/rsh -F "$@"
      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 [ "${ENSSH:-x}" != "x" ];then
	$ENSSH "$@" 
      else
	${krbdir}/rsh -F "$@"
      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
	OLDKRB5CCNAME="YES"
        KRB5CCNAME=/tmp/krb5cc_myjob_$$;export KRB5CCNAME
	${krbdir}/kcron 2> /dev/null
      fi
      if [ "${ENSSH:-x}" != "x" ];then
	$ENSSH "$@" 
      else
	${krbdir}/rsh -F "$@"
      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 [ "${ENSSH:-x}" != "x" ];then
    $ENSSH "$@" 
    exit $?
   fi
    rsh "$@"
    rc=$?
fi

set +xv
exit $rc
