#!/bin/bash -u
###########################################################
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/'
FULLPRINCIPAL="${WHOAMI}/cron/${NODENAME}@${REALM}"
KEYTAB="${KEYTABDIR}/${WHOAMI}.cron.${NODENAME}.keytab"
REMOVE_KEYTAB_UTIL='/usr/libexec/kcron/remove-kcron-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 [-n nodename] [-i identity]"         >&2
    echo "  The kcrondestroy utility deletes principal of the form"       >&2
    echo "  username/cron/host.domain@REALM from Kerberos realm. "      >&2
    echo "  " >&2
    echo ''                                    >&2
    exit 1
}


###########################################################
destroy() {
    # Destroy credential cache
    ${DESTROY_CACHE}
    echo " "
    echo DESTROYED administration credentials.
}


if [[ $? -ne 0 ]]; then
    usage
fi
###########################################################
#           CONFIRM 
###########################################################
echo " "
echo "WARNING!!!"
echo "kcrondestroy WILL REMOVE principal ${FULLPRINCIPAL} from Kerberos realm ${REALM}"
echo "and DELETE  keytab ${KEYTAB}."
echo "This principal is used by the kcron utility for authentication."
echo " "
echo " "
while true; do
    read -p "Do you want to continue? (y/n)" yn
    case ${yn} in
        [Yy]* ) break;;
        [Nn]* ) exit;;
        * ) echo "Please answer yes or no.";;
    esac
done

###########################################################
#           Check if Kerberos utilities are installed 
###########################################################

which kadmin >/dev/null 2>&1
if [[ $? -ne 0 ]]; then
    echo " "
    echo "Could not find 'kadmin'" >&2
    echo "Consider installing krb5-workstation" >&2
    exit 2
fi
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 klist >/dev/null 2>&1
if [[ $? -ne 0 ]]; then
    echo " "
    echo "Could not find 'klist'" >&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

kadmin=`which kadmin`
kinit=`which kinit`
klist=`which klist`    
DESTROY_CACHE=`which kdestroy`

###########################################################
#           SET UP CREDENTIAL CACHE
###########################################################
# In order to ask for password once need to obtain a ticket for kadmin/admin service
# Use temporary unique credential cache, which will be destroyed when kcron finishes. 
# KEYRING format must be 
# KEYRING:session:valid-uid:anything
# Get uid for current user 
MYUID=`id -u ${WHOAMI}`
SCRAMBLE=`date | md5sum | /bin/cut -f1 -d" "`
export KRB5CCNAME=KEYRING:session:${MYUID}:${SCRAMBLE}


###########################################################
#           Run
###########################################################
# Get credentials for service kadmin/admin, user is prompted for password
${kinit} -c ${KRB5CCNAME} -S kadmin/admin  > /dev/null >&2
if [ $? != 0 ]; then
    echo " "
    echo "Failed to obtain initial credentials"
    exit 2
fi


# Check if principal is in Kerberos database.
# I added  2> /dev/null to kadmin command to avoid message "Administration credentials NOT DESTROYED." 

PRINCIPAL_EXIST=`${kadmin} -p ${WHOAMI}@${REALM} -c ${KRB5CCNAME} -r ${REALM} -q "get_principal ${FULLPRINCIPAL}"  2> /dev/null | grep ${FULLPRINCIPAL}`
# For if does not exist, there is nothing to do
if [ "${PRINCIPAL_EXIST}" == '' ]; then
    echo Principal ${FULLPRINCIPAL} does not exist in Kerbreros ream ${REALM}
    echo NOTHING TO DO!
    destroy
    exit 0
else
   
    # Remove principal
    ${kadmin} -p ${WHOAMI}@${REALM} -c ${KRB5CCNAME} -r ${REALM} -q "delete_principal -force ${FULLPRINCIPAL}" 2> /dev/null 
    # Check if it is still there
    PRINCIPAL_EXIST=`${kadmin} -p ${WHOAMI}@${REALM} -c ${KRB5CCNAME} -r ${REALM} -q "get_principal ${FULLPRINCIPAL}" 2> /dev/null | grep ${FULLPRINCIPAL} `
    if [ "${PRINCIPAL_EXIST}" != '' ]; then
	echo " "
	echo "Cannot delete principal ${FULLPRINCIPAL} in realm ${REALM}."
	destroy
	exit 2
    fi
    destroy
fi

# Remove keytab file if exist
${REMOVE_KEYTAB_UTIL}
if [[ $? -eq 0 ]]; then
    echo SUCCESS!
fi
