#!/usr/bin/sh
###############################################################################
#                                                                             #
# File: kinit                                                                 #
#                                                                             #
# Wrapper to prefer MIT  version of kinit                                     #
# If only MIT is available, try to get AFS credentials                        #
###############################################################################

# @(#)kinit	1.2 Mon Nov  16 08:51:15 CET 2009 Jaroslaw.Polok@cern.ch

heimdal_kinit=/usr/heimdal/bin/kinit
mit_kinit=/usr/kerberos/bin/kinit

[ -x /usr/bin/kinit ] && mit_kinit=/usr/bin/kinit

afs5log=/usr/bin/afs5log
aklog=/usr/bin/aklog
eosfusebind=/usr/bin/eosfusebind

# do not get tokens for non-CERN realm
oldargs=$*
noncern=""

while [ -n "$1" ]; do
  arg=$1;
  shift;
  case "$arg" in
    *@cern.ch) ;;
    *@CERN.CH) ;;
    *@?*)
        noncern=1
        ;;
    esac
done

if [ -s "$mit_kinit" ]; then
  if [ -z "$noncern" ]; then
   # CERN-special treatment: get AFS
   $mit_kinit ${oldargs}
   ret=$?
   if [ $ret -ne 0 ]; then
     exit $ret
   fi
     # are we running AFS at all?
     # could use "fs" but segfaults and cannot hide?; df (slow on NFS); /proc (Linux-only); lsmod (dito)..
     if mount | grep -q /afs >/dev/null 2>&1; then
       if [ -s "$aklog" ]; then
        $aklog
       elif [ -s "$afs5log" ]; then
        $afs5log
       elif type -tp aklog >/dev/null; then
        aklog
       else
        echo "kinit: warn: cannot convert KRB5 to AFS token, neither afs5log nor aklog found"
       fi
     fi

    # do we have /eos present ?
    if [ -d /eos ]; then
      if [ -s "$eosfusebind" ]; then
       $eosfusebind
      fi
    fi
  else
   # non-CERN realm
   exec $mit_kinit ${oldargs};
  fi
elif [ -s "$heimdal_kinit" ]; then
  exec $heimdal_kinit ${oldargs}
else
  echo "kinit: error: neither MIT nor Heimdal kinit found"
  exit 1
fi
