#!/bin/bash -u

###########################################################
if [[ -r /etc/sysconfig/kcron ]]; then
    source /etc/sysconfig/kcron
fi
if [[ -r ~/.config/kcron ]]; then
    source ~/.config/kcron
fi

KEYTAB=$(${KEYTAB_NAME_UTIL:-/usr/libexec/kcron/client-keytab-name})
###########################################################
#
# Copyright 2023 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" >&2
    echo "  The kcrondestroy utility deletes principal of the form" >&2
    echo "  username/cron/host.domain@REALM from Kerberos realm. " >&2
    echo '' >&2
    echo '  Most values are sourced from /etc/sysconfig/kcron' >&2
    echo '  or ~/.config/kcron' >&2
    echo '' >&2
    exit 1
}

###########################################################
destroy() {
    # Destroy credential cache
    ${kdestroy}
    echo ''
    echo DESTROYED administration credentials.
}

###########################################################
#           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 -r -p 'Do you want to continue? (y/n)' yn
    case ${yn} in
    [Yy]*) break ;;
    [Nn]*) exit ;;
    *)
        echo "Please answer 'y' or 'n'."
        exit
        ;;

    esac
done

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

kadmin=$(which kadmin)
kinit=$(which kinit)
kdestroy=$(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=$(echo "$(
    date
    echo ${RANDOM}
)" | md5sum | /bin/cut -f1 -d" ")
export KRB5CCNAME="KEYRING:session:${MYUID}:${SCRAMBLE}"

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

# Check if principal is in Kerberos database.
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
if ! rm -f "${KEYTAB}"; then
    echo "SUCCESS!"
fi
