:
##########################################################################
# Title      :	expandvars - expand ${name} variables
# Author     :	Heiner Steven <heiner.steven@odn.de>
# Date       :	1999-07-04
# Requires   :	
# Category   :		
# SCCS-Id.   :	@(#) expandvars	1.1 04/02/29
##########################################################################
# Description
#
##########################################################################

PN=`basename "$0"`			# Program name
VER='1.1'

: ${Env:=../environment}

usage () {
    echo >&2 "$PN - expand environment variables, $VER
usage: $PN [-a] [-f envfile] [-vvar=value] [var ...]
    -a: expand all defined variables
    -f: specify file containing environment variable settings
        (may be specified more than once)
    -v: variable assignment, may be repeated

The variables specified on the command line are replaced with
their value.  If no variable was specified, all defined variables
are expanded."

    exit 1
}

msg () {
    for msgLine
    do echo "$PN: $msgLine" >&2
    done
}

fatal () { msg "$@"; exit 1; }

Vars=
if [ -r "$Env" ]
then
    . "$Env"
    Vars=`grep '^[a-zA-z_0-9][a-zA-z_0-9]*=' < "$Env" | cut -d= -f1`
fi

# We need two passes through the argument list, because
# we always want to read the "$Env" file before changing
# variable values using "-v". The file may be specified
# using the "-f" option.
Options=af:hv:
while getopts $Options opt
do
    case "$opt" in
	f)
	    varfile="$OPTARG"
	    [ -r "$varfile" ] && . "$varfile"
	    Vars=${Vars:+$Vars }`grep '^[a-zA-z_0-9][a-zA-z_0-9]*=' < "$varfile" | cut -d= -f1`
	    ;;
    esac
done

append=no
assign=
OPTIND=1			# Reset index in argument list for getopts
while getopts $Options opt
do
    case "$opt" in
        a)	append=yes;;
	f)	;;
	h)	usage;;
	v)	
		var=`expr "$OPTARG" : '\([^=][^=]*\)=.*'`
		val=`expr "$OPTARG" : '[^=]*=\(.*\)'`
		if [ -n "$var" ]
		then
		    eval $var='$'val
		    assign="${assign:+$assign }$var"
		fi;;
	?)	usage;;
    esac
done
shift `expr $OPTIND - 1`

if [ $# -gt 0 ]
then
    if [ $append = yes ]
    then set -- $Vars $assign "$@"
    else set -- $assign "$@"
    fi
else
    set -- $Vars $assign "$@"
fi

SedScript=${TMPDIR:=/tmp}/exp$$.sed
Tmp=$TMPDIR/exp$$.tmp
trap 'rm -f "$SedScript" "$Tmp" >/dev/null 2>&1' 0
trap "exit 2" 1 2 3 15

[ $# -lt 1 ] && fatal "please specify variables to expand"

for var
do
    eval val=$`echo "$var"`
    echo "s\${$var}$valg;"
done > "$SedScript"

sed -f "$SedScript"
