#!/bin/sh
# usage: rbuttonfly <topbuttonname> [topdirectory]


# Check the usage

if [ "$#" -lt "1" -o "$#" -gt "2" ]; then
	echo "usage: rbuttonfly <topbuttonname> [topdirectory]"
	exit 1
fi


# Assign the local argument vars

topmenu="/usr/tmp/.menu$$"
topbutton="$1"
topdirectory="${2:-.}"


# Assign default values to all of the environment vars that are not set

RBF_DIRPAT=${RBF_DIRPAT:-*.ddir}
RBF_FILPAT=${RBF_FILPAT:-*.demo}

if [ "${RBF_DIRCMD:-unset}" = "unset" ]; then
	RBF_DIRCMD="sed -e 's/\..*$//' -e 's/_/ /g'"
fi
if [ "${RBF_FILCMD:-unset}" = "unset" ]; then
	RBF_FILCMD="sed -e 's/\..*$//' -e 's/_/ /g'"
fi

RBF_DIRCLR=${RBF_DIRCLR:-'0.387 0.035 0.102'}
RBF_DIRHLT=${RBF_DIRHLT:-'0.621 0.059 0.160'}
RBF_DIRBCK=${RBF_DIRBCK:-'0.204 0.204 0.204'}

RBF_FILCLR=${RBF_FILCLR:-'0.035 0.278 0.384'}
RBF_FILHLT=${RBF_FILHLT:-'0.055 0.463 0.639'}

# Export all of the environment vars

export RBF_DIRPAT RBF_FILPAT RBF_DIRCMD RBF_FILCMD
export RBF_DIRCLR RBF_DIRHLT RBF_DIRBCK
export RBF_FILCLR RBF_FILHLT


# Assign the key local vars

b="\\"
t="\t"
q="'"
line='                                                                        \
	for dir in $RBF_DIRPAT;						      \
	do								      \
		if [ -d "$dir" ];					      \
		then							      \
			eval "echo $dir | $RBF_DIRCMD";			      \
			echo "${t}.color. $RBF_DIRCLR";			      \
			echo "${t}.highcolor. $RBF_DIRHLT";		      \
			echo "${t}.backcolor. $RBF_DIRBCK";		      \
			echo "${t}.cd. $dir";				      \
			echo "${t}b=\"$b$b$b$b\" t=\"${b}${b}t\" q=\"$q\" line=${q}$line${q}; eval \$line"; \
			echo "${t}.menu. -";				      \
			echo;						      \
		fi;							      \
	done;								      \
	for run in $RBF_FILPAT;						      \
	do								      \
		if [ -x "$run" ];					      \
		then							      \
			eval "echo $run | $RBF_FILCMD";			      \
			echo "${t}.color. $RBF_FILCLR";			      \
			echo "${t}.highcolor. $RBF_FILHLT";		      \
			echo "${t}./$run";				      \
			echo;						      \
		fi;							      \
	done';


# Translate the $line var, removing the backslashes

line=`echo $line | sed -e 's/\\\ //g'`


# Write out the top level menu

cat >$topmenu <<EOF
	.backcolor. $RBF_DIRBCK
$topbutton
	.color. $RBF_DIRCLR
	.highcolor. $RBF_DIRHLT
	.backcolor. $RBF_DIRBCK
	.cd. $topdirectory
	b="$b$b" t="${b}t" q="$q" line=${q}$line${q}; eval \$line
	.menu. -
EOF


# Start buttonfly!

buttonfly $topmenu

# Remove the menu

rm /usr/tmp/.menu$$
