#!/bin/bash

# ----------------------------------------------------------------------
# File: eos-test-credential-bindings
# Author: Manuel Reis
# ----------------------------------------------------------------------
################################################################################################################
# Usage:                                                                                                       #
# bash> eos-test-credential-bindings  <localmount directory to test>									 	   #
################################################################################################################

FUSEDIR=${1:-"/eos/dockertest/test"}
USER="$(id -un)"
CURRENT_KRB5CCNAME=${KRB5CCNAME}
restore_krb5ccname () {
	export KRB5CCNAME=${CURRENT_KRB5CCNAME}
	
	# Remove global binding
	find /var/run/eos/credentials/ -type f -user ${USER} -exec rm -rf {} + 
}
trap restore_krb5ccname EXIT


testglobalbinding () {
	echo "${USER} is testing access to local mount point: ${FUSEDIR}"
    kdestroy # destroy valid (default credentials?!)
    export KRB5CCNAME=/tmp/nonstandard.krb5
    kinit eos-user@TEST.EOS -k -t /home/eos-user/eos-user.keytab || kinit
        if [[ $? -ne 0 ]]; then
        echo "Unable to obtain valid credentials in the first place... Aborting"
        exit 1
    fi
    
	
    mkdir -m 700 -p ${FUSEDIR}/${USER} && touch ${FUSEDIR}/${USER}/ola && /bin/ls ${FUSEDIR}/${USER}/ > /dev/null
    if [[ $? -ne 0 ]]; then
        echo "Failed initial test (mkdir + touch + ls) : $?"
        exit 2
    fi

	# should have permission denied, if mount point SSS configuration is disabled
    env -u KRB5CCNAME /bin/ls ${FUSEDIR}/${USER}/ 2> /dev/null
    if [[ $? -ne 2 ]]; then
        echo "Permission denied is expected but ls returned: $?"
        exit 3
    fi
    
    # binding credentials so that the subprocess can access
    eosfusebind -g

    env -u KRB5CCNAME /bin/ls ${FUSEDIR}/${USER}/ > /dev/null
    if [[ $? -ne 0 ]]; then
        echo "Should have permissions in credentials directory: $?"
        exit 4
    fi

    rm -rf ${FUSEDIR}/${USER}
}

testglobalbinding