#
# $Id: shell_subs.sh,v 1.1 2003/12/09 22:27:18 ehaszla Exp $
# 

# This file contains usefull shell functions
# It should be loaded like so:
# . /path/to/here/shell_subs.sh

#
# add_cvar
#   Add an element to a variable containing colon separated data.
# Identical elements will only be added once.
#
# add_cvar [-p] <varname> <newval>
#   -p: Prefix the new data
#
add_cvar()
{
	local prefix varname newval
	prefix=0
	if [ "$1" = "-p" ] ; then
		prefix=1
		shift
	fi
	varname=$1
	newval=$2

	rm_cvar "$1" "$2" || return 1

	oldval=`eval echo \"\\${$varname}\"`    
	if echo ":$oldval:" | grep -q ":$newval:" ; then
		return
	fi
	if eval [ -z \"\${$varname}\" ] ; then
		eval ${varname}=\""$newval"\"
		return
	fi
	if [ $prefix -eq 1 ] ; then
		eval ${varname}=\""\$newval:\${$varname}"\"
	else
		eval ${varname}=\""\${$varname}:\$newval"\"
	fi
}

#
# rm_cvar
#   Remove an element from a variable containing colon separated data.
#
# rm_cvar [-a] <varname> <delval>
#   -a: Remove all instance of the element, not just the first one.
#
rm_cvar()
{
	local doall varname delval
	local seddel oldval newval
	doall=0
	if [ "$1" = "-a" ] ; then
		doall=1
		shift
	fi
	varname=$1
	delval=`echo "$2" | sed -e's,\\\\,\\\\\\\\,g' -e's,/,\\\\/,g' `
	while true ; do
		oldval=`eval echo \"\\${$varname}\"`
	newval=`echo ":${oldval}:" | sed -e"s/:${delval}:/:/" -e's/^://' -e's/:$//'`
		eval ${varname}=\"\${newval}\"
		if [ $doall -eq 0 ] ; then
			break
		fi
		if [ -z "${newval}" -o "${newval}" = "${oldval}" ] ; then
			break
		fi
	done
}

