##############################################################################
# Copyright (c) Members of the EGEE Collaboration. 2004. 
# See http://www.eu-egee.org/partners/ for details on the copyright 
# holders.  
#
# Licensed under the Apache License, Version 2.0 (the "License"); 
# you may not use this file except in compliance with the License. 
# You may obtain a copy of the License at 
#
#    http://www.apache.org/licenses/LICENSE-2.0 
#
# Unless required by applicable law or agreed to in writing, software 
# distributed under the License is distributed on an "AS IS" BASIS, 
# WITHOUT WARRANTIES OR CONDITIONS 
# OF ANY KIND, either express or implied. 
# See the License for the specific language governing permissions and 
# limitations under the License.
##############################################################################
#
# NAME :        config_add_glite_env
#
# DESCRIPTION : This function configures the /etc/profile.d/glite_setenv.sh file.
#
# AUTHORS :     Robert.Harakaly@cern.ch
#
# NOTES :      
#
# YAIM MODULE:  glite-yaim-core
#                 
##############################################################################

config_add_glite_env(){
    echo "Adding glite_setenv.* to /etc/profile.d"
	if [ ! -f /etc/profile.d/glite_setenv.sh ]; then
		cat << EOF > /etc/profile.d/glite_setenv.sh
#	Source default glite environment file
if [ -f /etc/glite/profile.d/glite_setenv.sh ]; then
	. /etc/glite/profile.d/glite_setenv.sh
fi
EOF
	fi
	if [ ! -f /etc/profile.d/glite_setenv.csh ]; then
		cat << EOF > /etc/profile.d/glite_setenv.csh
#	Source default glite environment file
if ( -f /etc/glite/profile.d/glite_setenv.csh ) then
	source /etc/glite/profile.d/glite_setenv.csh
endif
EOF
	fi

	echo 'Add glite_setenv.* to all pool accounts for ${VOS}'
	while IFS=: read id user gid group virtorg tag other; do
    	# Skip user if VO not supported
    	if ! ( [ "$virtorg" ] && echo $VOS | grep -w "$virtorg" >/dev/null ); then
        	continue
    	fi

    	# Modify ~$user/.bashrc for pool account
    	user_rc=`eval echo ~${user}/.bashrc`
    	touch $user_rc
    	if ( ! ( cat $user_rc | grep -q glite_setenv.sh )); then
        	cat <<EOF >> $user_rc
if [ -f /etc/glite/profile.d/glite_setenv.sh ]; then
        . /etc/glite/profile.d/glite_setenv.sh
fi
EOF
    	fi

    	# Modify .cshrc for pool account
    	user_rc=`eval echo ~${user}/.cshrc`
    	touch $user_rc
    	if ( ! ( cat $user_rc | grep -q glite_setenv.csh )); then
        	cat <<EOF >> $user_rc
if ( -f /etc/glite/profile.d/glite_setenv.csh ) then
        source /etc/glite/profile.d/glite_setenv.csh
endif
EOF
    	fi
	done < $USERS_CONF
	return 0
}
