#!/bin/bash
# -*- mode: shell-script; coding: utf-8 -*-
#
# Copyright 2002-2013 Cendio AB.
# For more information, see http://www.cendio.com
#
# action: Obtaining Kerberos ticket
#

if type kinit; then
    if [ -z "${KRB5CCNAME}" ]; then
        export KRB5CCNAME="${TLSESSIONDATA}/krb5cc"
    fi
    # -l without argument gives usage with both MIT and Heimdal
    if kinit -l 2>&1 | grep password-file >/dev/null; then
        # Heimdal
        stdin_arg="--password-file=STDIN"
    else
	# MIT
        stdin_arg=""
    fi
    if "${TLPREFIX}/bin/tl-sso-token-passphrase" --check; then
        "${TLPREFIX}/bin/tl-sso-token-passphrase" | kinit ${stdin_arg}
    elif "${TLPREFIX}/bin/tl-sso-password" --check; then
        "${TLPREFIX}/bin/tl-sso-password" | kinit ${stdin_arg}
    fi
    if type afslog; then
	# Try to find a Kerberos ticket from the login session
	if [ ! -f $KRB5CCNAME ]; then
	    uid=`id -u`
	    tkt=`find /tmp -user $USER -type f -size +0 -name krb5cc_${uid}_\* 2>/dev/null | xargs ls -lart | tail -n 1 | awk '{print $NF}'`
	    if [ -f $tkt ]; then
		mv $tkt $KRB5CCNAME
	    fi
	fi
	afslog
    fi
fi
