#!/bin/bash 
###########################################################
REALM='FNAL.GOV'
config=${KRB5_CONFIG:-'/etc/krb5.conf'}
ISPILOT=`cat ${config} 2> /dev/null | grep default_realm | grep PILOT.FNAL.GOV`
if [ "${ISPILOT}" != "" ]
then
    REALM='PILOT.FNAL.GOV'
fi
WHOAMI=$(basename $(whoami))
NODENAME=$(basename $(hostname))
KEYTABDIR='/var/adm/krb5/'
RUN_COMMAND=${@}
FULLPRINCIPAL="${WHOAMI}/cron/${NODENAME}@${REALM}"
KEYTAB="${KEYTABDIR}/${WHOAMI}.cron.${NODENAME}.keytab"

###########################################################
#
# Copyright 2017 Fermi Research Alliance, LLC
#
# This software was produced under U.S. Government contract DE-AC02-07CH11359 for Fermi National Accelerator Laboratory (Fermilab), which is operated by Fermi Research Alliance, LLC for the U.S. Department of Energy. The U.S. Government has rights to use, reproduce, and distribute this software.  NEITHER THE GOVERNMENT NOR FERMI RESEARCH ALLIANCE, LLC MAKES ANY WARRANTY, EXPRESS OR IMPLIED, OR ASSUMES ANY LIABILITY FOR THE USE OF THIS SOFTWARE.  If software is modified to produce derivative works, such modified software should be clearly marked, so as not to confuse it with the version available from Fermilab.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR FERMI RESEARCH ALLIANCE, LLC BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
###########################################################
#               Functions
###########################################################
usage() {
    echo ''            >&2
    echo "$0 [command]">&2
    echo '  The kcron utility obtains Kerberos credentials for a process'   >&2
    echo '  using a keytab previously created by kcroninit.  The principal' >&2
    echo '  used in that keytab is of the form:' >&2
    echo '    username/cron/host.domain@REALM.'  >&2
    echo ''            >&2
    echo '  The kerberos credentials are stored in protected'>&2
    echo '  memory and not exposed on the filesystem'        >&2
    echo ''            >&2
    echo '  Examples:'                           >&2
    echo "$0 ls"                                 >&2
    echo "$0 ls -a -l"                           >&2
    exit 1
}

###########################################################

if [[ $# -eq 0 ]] ; then
    usage
fi

###########################################################
#           Check if Kerberos utilities are installed 
###########################################################
which kinit >/dev/null 2>&1
if [[ $? -ne 0 ]]; then
    echo " "
    echo "Could not find 'kinit'" >&2
    echo "Consider installing krb5-workstation" >&2
    exit 2
fi
which logger >/dev/null 2>&1
if [[ $? -ne 0 ]]; then
    echo " "
    echo "Could not find 'logger'" >&2
    echo "Consider installing util-linux" >&2
    exit 2
fi
which md5sum >/dev/null 2>&1
if [[ $? -ne 0 ]]; then
    echo " "
    echo "Could not find 'md5sum'" >&2
    echo "Consider installing coreutils" >&2
    exit 2
fi
which id >/dev/null 2>&1
if [[ $? -ne 0 ]]; then
    echo " "
    echo "Could not find 'id'" >&2
    echo "Consider installing coreutils" >&2
    exit 2
fi

DESTROY_CACHE=`which kdestroy`
kinit=`which kinit`
logger=`which logger`
md5sum=`which md5sum`
id=`which id`

###########################################################
#           SET UP CREDENTIAL CACHE
###########################################################
# Use temporary unique credential cache, which will be destroyed when kcron finishes. 
# In order to use KEYRING, the format must be 
# KEYRING:session:valid-uid:anything

if [[ ! -r ${KEYTAB} ]]; then
    echo " "
    echo "Could not read '${KEYTAB}'" >&2
    echo "Consider running kcroninit" >&2
    exit 2
fi

MYUID=`${id} -u ${WHOAMI}`
SCRAMBLE=`date | ${md5sum} | /bin/cut -f1 -d" "`
export KRB5CCNAME=KEYRING:session:${MYUID}:${SCRAMBLE}
#echo ${KRB5CCNAME}

###########################################################
#           Run
###########################################################
# Obtain credentials for cron principal
${kinit} -kt ${KEYTAB} ${FULLPRINCIPAL}

if [[ $? -eq 0 ]]; then
    ${logger} -t Kerberos -p auth.notice "kcron obtained credentials for ${FULLPRINCIPAL}"
else
    RC=$?
    ${logger} -t Kerberos -p auth.warning "kcron failed for ${FULLPRINCIPAL}"
    echo "kcron failed for ${FULLPRINCIPAL}" >&2
    exit ${RC}
fi

# Run command, record in the system log
${logger} -t Kerberos -p auth.debug "kcron running ${RUN_COMMAND}"
${RUN_COMMAND}
echo " "
${DESTROY_CACHE}

