#!/bin/sh
# tips: shell tips and other for muLinux
# (C) M. Andreoli 2000

# Execute/browse command in /usr/tips/items, organized
# in category (directory)

. /etc/color
. /etc/dialog.lib

#set -x

BACK_TITLE="Scripting tips in muLinux"

#set -x

pick()
{
local n=$1
skip=`expr $n - 1`
/bin/ls -1 | tail +$skip | (read line; echo $line) 
}

menu_type()
{
pwd=`pwd`
case $pwd in
/usr/tips/items)	echo "categories";;
*)			echo "commands in [`basename $pwd`] category";;
esac 
}


view_txt()
{
local item=$1
echo
        read -p "View source for this command (y/n)? [n] " view
        [ -z "$view" ] && view=n
        [ $view = y ] && muless -l $item
}

view_dia()
{
local item=$1
#dialog --clear
read -p "press -ENTER- to continue" enter
dyesno -t Question "View source for this command?"
r=`result`
case $r in
-yes-)
	#muless -b "q)uit" -l $item
	TITLE="`basename $item`"
	dbrowse  -t $TITLE -r 10 -c 50 $item 
	DIM=
	;;
esac

}

process()
{
local item=$1

if [ -d "$item" ] ; then
	cd $item
else
	. $item
	eval view_$mode $item
fi

}


select_txt()
{
clear
echo "Available `menu_type`:"
echo -e "$BRIGHT"
/bin/ls -1F | cat -n
echo -e "$NORMAL"
read -p "Select a number ([b]ack [q]uit)> " n
}

select_dia()
{
TITLE=$( echo "Available `menu_type`:" | tr ' ' _)
dmenu -t $TITLE $(/bin/ls -1q | cat -n | quote)
n=`result`

case $n in
-no-)  n=b;;
esac

}

list()
{
while [ 1 ] ; do

eval select_$mode

case $n in
q)	echo "Bye!"; exit;;
b)	
	pwd=`pwd`	
	[ "$pwd" = "/usr/tips/items" ] && exit
	cd .. ;;
*)
	process `pick $n`
	;;
esac


done
}

#----------
# Main
#----------

# determine 'mode'

if [ "`which dialog`" ] ; then
	mode=dia
else
	mode=txt
fi


mode=${1:-$mode}
cd /usr/tips/items
list
