#!/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_INIT='/usr/libexec/kcron/init-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 "  The kcroninit utility creates a new principal of the form"       >&2
    echo "  username/cron/host.domain@REALM  and then creates a keytab"      >&2
    echo "  file that can be used by the kcron utility for authentication. " >&2
    echo ''                                    >&2
    exit 1
}

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

#if [[ $# -ne 0 ]]; then
#    usage
#fi
###########################################################
#        Opions
###########################################################
# When cron principal keytab is created for shared accounts 
# which do not have a Kerberos principal, admin principal will be 
# cron principal itself. It is assumed that Service Desk already
# created the principal and only keytab is needed.
# Reglar users are able to use their Kerberos principals to create cron principals.

ADMPRINCIPAL=${WHOAMI}
if [[ $# -ne 0 ]]; then
    args=$(getopt -o sh )
    if [[ $? -ne 0 ]]; then
	usage
    fi
    for arg in $args; do
	case $1 in
	    
            -- )
		break 2
		;;
            -s )
		ADMPRINCIPAL=${WHOAMI}/cron/${NODENAME}
		;;
            -h )
            # get help
		usage
		;;
	esac
    done
fi

###########################################################
#           CONFIRM 
###########################################################
echo "kcroninit creates principal ${FULLPRINCIPAL} and/or extracts its keys into a keytab."
echo "This principal is used by the kcron utility for authentication."
echo "You need to know the password for ${ADMPRINCIPAL} to continue."
while true; do
    read -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 
###########################################################

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}

###########################################################
#           Can write to keytab? 
###########################################################
echo " "
echo "Checking permissions for ${KEYTABDIR} ..."
KEYTAB=$(${KEYTAB_INIT})
if [[ $? -ne 0 ]]; then
    exit 2
fi

###########################################################
#           Run
###########################################################

# Obtain credentials
echo " "
${kinit} -c ${KRB5CCNAME} -S kadmin/admin  ${ADMPRINCIPAL}@${REALM} >/dev/null >&2
if [ $? != 0 ]; then
    echo " "
    echo "Failed to obtain initial credentials. Exiting..."
    destroy
    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 ${ADMPRINCIPAL}@${REALM} -c ${KRB5CCNAME} -r ${REALM} -q "get_principal ${FULLPRINCIPAL}"  2> /dev/null | grep ${FULLPRINCIPAL}  `
echo ${PRINCIPAL_EXIST}

# Skip create for existing principals, create otherwise

if [ "${PRINCIPAL_EXIST}" != '' ]; then
	echo " "
	echo "Principal ${FULLPRINCIPAL} already exists in Kerberos database."
else
    echo "Creating principal..."
    # Create principal
    ${kadmin} -p ${ADMPRINCIPAL}@${REALM} -c ${KRB5CCNAME} -r ${REALM} -q "add_principal -randkey -pwexpire never ${FULLPRINCIPAL}" 2> /dev/null
    
    # Check if created successfully
    PRINCIPAL_EXIST=`${kadmin} -p ${ADMPRINCIPAL}@${REALM} -c ${KRB5CCNAME} -r ${REALM} -q "get_principal ${FULLPRINCIPAL}"  2> /dev/null | grep ${FULLPRINCIPAL} `
    if [ "${PRINCIPAL_EXIST}" == '' ]; then
	echo " "
	echo "Cannot create principal ${FULLPRINCIPAL} in realm ${REALM}. Exiting..."
	destroy
	exit 2
    fi
    
fi	
       
# Extract keytab
echo "Extracting keytab..."
${kadmin} -p ${ADMPRINCIPAL}@${REALM} -c ${KRB5CCNAME} -r ${REALM} -q "ktadd -k ${KEYTAB} ${FULLPRINCIPAL}"  2> /dev/null
# Verify
PRINCIPAL_IN_KEYTAB=`${klist} -k ${KEYTAB} | grep ${FULLPRINCIPAL}   `
if [ "${PRINCIPAL_IN_KEYTAB}" == '' ]; then
	echo " "
	echo "Unable to extract ${FULLPRINCIPAL} keys into keytab ${KEYTAB}. Exiting..."
    exit 2
else
	echo " "
	echo "Created keytab ${KEYTAB} "
	${klist} -k ${KEYTAB} | grep ${FULLPRINCIPAL}

fi

destroy
echo DONE!
